Вроде готово, потом мб поправлю

This commit is contained in:
Andrey 2024-10-16 13:08:07 +03:00
parent 82d134aeab
commit 358a381e20
54 changed files with 4354 additions and 257 deletions

View File

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Contracts\Contracts.csproj" />
<ProjectReference Include="..\DataModels\DataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,163 @@
using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using Contracts.SearchModels;
using Contracts.StorageContracts;
using Contracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLogics.BusinessLogics
{
public class DishLogic : IDishLogic
{
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Хранилище
/// </summary>
private readonly IDishStorage _dishStorage;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="logger"></param>
/// <param name="dishStorage"></param>
public DishLogic(ILogger<DishLogic> logger, IDishStorage dishStorage)
{
_logger = logger;
_dishStorage = dishStorage;
}
/// <summary>
/// Получить список записией
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<DishViewModel>? ReadList(DishSearchModel? model)
{
_logger.LogInformation("ReadList. Dish.Id: {Id}", model?.Id);
var list = model == null ? _dishStorage.GetFullList() : _dishStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList. Returned null list");
return null;
}
_logger.LogInformation("ReadList. Count: {Count}", list.Count);
return list;
}
/// <summary>
/// Получить отдельную запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public DishViewModel? ReadElement(DishSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Dish.Id: {Id}", model?.Id);
var element = _dishStorage.GetElement(model!);
if (element == null)
{
_logger.LogWarning("ReadElement. Element not found");
return null;
}
_logger.LogInformation("ReadElement. Find Dish.Id: {Id}", element.Id);
return element;
}
/// <summary>
/// Создать запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Create(DishBindingModel model)
{
CheckModel(model);
_logger.LogInformation("Create. Dish.Id: {Id}", model.Id);
if (_dishStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
/// <summary>
/// Изменить запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Update(DishBindingModel model)
{
CheckModel(model);
_logger.LogInformation("Update. Dish.Id: {Id}", model.Id);
if (_dishStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
/// <summary>
/// Удалить запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Delete(DishBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Dish.Id: {Id}", model.Id);
if (_dishStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
/// <summary>
/// Проверить модель
/// </summary>
/// <param name="model"></param>
/// <param name="withParams"></param>
/// <exception cref="ArgumentNullException"></exception>
private void CheckModel(DishBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Не указано название блюда", nameof(model.Name));
}
_logger.LogInformation("CheckModel. Dish.Id: {Id}", model.Id);
}
}
}

View File

@ -0,0 +1,166 @@
using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using Contracts.SearchModels;
using Contracts.StorageContracts;
using Contracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLogics.BusinessLogics
{
public class OrderLogic : IOrderLogic
{
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Хранилище
/// </summary>
private readonly IOrderStorage _orderStorage;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="logger"></param>
/// <param name="orderStorage"></param>
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
{
_logger = logger;
_orderStorage = orderStorage;
}
/// <summary>
/// Получить список записией
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. Order.Id: {Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList. Returned null list");
return null;
}
_logger.LogInformation("ReadList. Count: {Count}", list.Count);
return list;
}
/// <summary>
/// Получить отдельную запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public OrderViewModel? ReadElement(OrderSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Order.Id: {Id}", model?.Id);
var element = _orderStorage.GetElement(model!);
if (element == null)
{
_logger.LogWarning("ReadElement. Element not found");
return null;
}
_logger.LogInformation("ReadElement. Find Order.Id: {Id}", element.Id);
return element;
}
/// <summary>
/// Создать запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Create(OrderBindingModel model)
{
CheckModel(model);
_logger.LogInformation("Create. Order.Id: {Id}", model.Id);
if (_orderStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
/// <summary>
/// Изменить запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Update(OrderBindingModel model)
{
CheckModel(model);
_logger.LogInformation("Update. Order.Id: {Id}", model.Id);
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
/// <summary>
/// Удалить запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Delete(OrderBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Order.Id: {Id}", model.Id);
if (_orderStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.WaiterFullName))
{
throw new ArgumentNullException("Не указано ФИО официанта", nameof(model.WaiterFullName));
}
if (string.IsNullOrEmpty(model.Dish))
{
throw new ArgumentNullException("Не указано заказанное блюдо", nameof(model.Dish));
}
if (string.IsNullOrEmpty(model.PicturePath))
{
throw new ArgumentNullException("Не указан скан счета", nameof(model.PicturePath));
}
_logger.LogInformation("CheckModel. Order.Id: {Id}", model.Id);
}
}
}

View File

@ -5,7 +5,18 @@ VisualStudioVersion = 17.11.35222.181
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Components", "Components.csproj", "{81DCA34B-4D91-4C79-A0CC-65F1DB3BCC18}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestForm", "..\TestForm\TestForm.csproj", "{4E72B9A4-3B1A-4699-B103-CBE4558F5E66}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BusinessLogics", "..\BusinessLogics\BusinessLogics.csproj", "{9CAF8B8B-62FC-49BB-BFAF-A041B00DC273}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Contracts", "..\Contracts\Contracts.csproj", "{F92B9F62-A158-4AFF-A89E-A1F3535A3938}"
ProjectSection(ProjectDependencies) = postProject
{FB13C40F-4FBA-4A3E-970B-B819088AF3C5} = {FB13C40F-4FBA-4A3E-970B-B819088AF3C5}
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DatabaseImplement", "..\DatabaseImplement\DatabaseImplement.csproj", "{76CE2845-2A17-4AB2-B858-E5C59D9BAAC3}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DataModels", "..\DataModels\DataModels.csproj", "{FB13C40F-4FBA-4A3E-970B-B819088AF3C5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WinForms", "..\WinForms\WinForms.csproj", "{A76DC396-93E5-4901-9A18-0E7590457772}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -17,10 +28,26 @@ Global
{81DCA34B-4D91-4C79-A0CC-65F1DB3BCC18}.Debug|Any CPU.Build.0 = Debug|Any CPU
{81DCA34B-4D91-4C79-A0CC-65F1DB3BCC18}.Release|Any CPU.ActiveCfg = Release|Any CPU
{81DCA34B-4D91-4C79-A0CC-65F1DB3BCC18}.Release|Any CPU.Build.0 = Release|Any CPU
{4E72B9A4-3B1A-4699-B103-CBE4558F5E66}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4E72B9A4-3B1A-4699-B103-CBE4558F5E66}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4E72B9A4-3B1A-4699-B103-CBE4558F5E66}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4E72B9A4-3B1A-4699-B103-CBE4558F5E66}.Release|Any CPU.Build.0 = Release|Any CPU
{9CAF8B8B-62FC-49BB-BFAF-A041B00DC273}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9CAF8B8B-62FC-49BB-BFAF-A041B00DC273}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9CAF8B8B-62FC-49BB-BFAF-A041B00DC273}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9CAF8B8B-62FC-49BB-BFAF-A041B00DC273}.Release|Any CPU.Build.0 = Release|Any CPU
{F92B9F62-A158-4AFF-A89E-A1F3535A3938}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F92B9F62-A158-4AFF-A89E-A1F3535A3938}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F92B9F62-A158-4AFF-A89E-A1F3535A3938}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F92B9F62-A158-4AFF-A89E-A1F3535A3938}.Release|Any CPU.Build.0 = Release|Any CPU
{76CE2845-2A17-4AB2-B858-E5C59D9BAAC3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{76CE2845-2A17-4AB2-B858-E5C59D9BAAC3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{76CE2845-2A17-4AB2-B858-E5C59D9BAAC3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{76CE2845-2A17-4AB2-B858-E5C59D9BAAC3}.Release|Any CPU.Build.0 = Release|Any CPU
{FB13C40F-4FBA-4A3E-970B-B819088AF3C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FB13C40F-4FBA-4A3E-970B-B819088AF3C5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FB13C40F-4FBA-4A3E-970B-B819088AF3C5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FB13C40F-4FBA-4A3E-970B-B819088AF3C5}.Release|Any CPU.Build.0 = Release|Any CPU
{A76DC396-93E5-4901-9A18-0E7590457772}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A76DC396-93E5-4901-9A18-0E7590457772}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A76DC396-93E5-4901-9A18-0E7590457772}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A76DC396-93E5-4901-9A18-0E7590457772}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataModels.Models;
namespace Contracts.BindingModels
{
public class DishBindingModel : IDishModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; set; }
/// <summary>
/// Название блюда
/// </summary>
public string Name { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,38 @@
using DataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Contracts.BindingModels
{
public class OrderBindingModel : IOrderModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; set; }
/// <summary>
/// ФИО официанта
/// </summary>
public string WaiterFullName { get; set; } = string.Empty;
/// <summary>
/// Информация по счету
/// </summary>
public string PicturePath { get; set; } = string.Empty;
/// <summary>
/// Тип заказа
/// </summary>
public string Dish { get; set; } = string.Empty;
/// <summary>
/// Сумма заказа
/// </summary>
public DateTime OrderDate { get; set; }
}
}

View File

@ -0,0 +1,50 @@
using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Contracts.BusinessLogicsContracts
{
public interface IDishLogic
{
/// <summary>
/// Получить список записией
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
List<DishViewModel>? ReadList(DishSearchModel? model);
/// <summary>
/// Получить отдельную запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
DishViewModel? ReadElement(DishSearchModel model);
/// <summary>
/// Создать запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
bool Create(DishBindingModel model);
/// <summary>
/// Изменить запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
bool Update(DishBindingModel model);
/// <summary>
/// Удалить запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
bool Delete(DishBindingModel model);
}
}

View File

@ -0,0 +1,52 @@
using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Contracts.BusinessLogicsContracts
{
/// <summary>
/// Интерфейс для описания работы бизнес-логики для сущности "Счет"
/// </summary>
public interface IOrderLogic
{
/// <summary>
/// Получить список записией
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
List<OrderViewModel>? ReadList(OrderSearchModel? model);
/// <summary>
/// Получить отдельную запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
OrderViewModel? ReadElement(OrderSearchModel model);
/// <summary>
/// Создать запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
bool Create(OrderBindingModel model);
/// <summary>
/// Изменить запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
bool Update(OrderBindingModel model);
/// <summary>
/// Удалить запись
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
bool Delete(OrderBindingModel model);
}
}

View File

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DataModels\DataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Contracts.SearchModels
{
public class DishSearchModel
{
public int? Id { get; set; }
public string? Name { get; set; }
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Contracts.SearchModels
{
public class OrderSearchModel
{
public int? Id { get; set; }
public string? WaiterFullName { get; set; }
public string Dish { get; set; }
public DateTime OrderDate { get; set; }
}
}

View File

@ -0,0 +1,26 @@
using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Contracts.StorageContracts
{
public interface IDishStorage
{
List<DishViewModel> GetFullList();
List<DishViewModel> GetFilteredList(DishSearchModel model);
DishViewModel? GetElement(DishSearchModel model);
DishViewModel? Insert(DishBindingModel model);
DishViewModel? Update(DishBindingModel model);
DishViewModel? Delete(DishBindingModel model);
}
}

View File

@ -0,0 +1,27 @@
using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Contracts.StorageContracts
{
public interface IOrderStorage
{
List<OrderViewModel> GetFullList();
List<OrderViewModel> GetFilteredList(OrderSearchModel model);
OrderViewModel? GetElement(OrderSearchModel model);
OrderViewModel? Insert(OrderBindingModel model);
OrderViewModel? Update(OrderBindingModel model);
OrderViewModel? Delete(OrderBindingModel model);
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Contracts.ViewModels
{
public class DishViewModel
{
public int Id { get; set; }
[DisplayName("Название блюда")]
public string Name { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Contracts.ViewModels
{
public class OrderViewModel
{
public int Id { get; set; }
[DisplayName("ФИО официанта")]
public string WaiterFullName { get; set; } = string.Empty;
[DisplayName("Заказанное блюдо")]
public string Dish { get; set; } = string.Empty;
public string PicturePath { get; set; } = string.Empty;
[DisplayName("Дата заказа")]
public DateTime OrderDate { get; set; }
}
}

View File

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

20
DataModels/IId.cs Normal file
View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataModels
{
/// <summary>
/// Интерфейс для идентификатора
/// </summary>
public interface IId
{
/// <summary>
/// Идентификатор
/// </summary>
int Id { get; }
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace DataModels.Models
{
/// <summary>
/// Интерфейс для сущности "Заказанное блюдо"
/// </summary>
public interface IDishModel : IId
{
/// <summary>
/// Название блюда
/// </summary>
string Name { get; }
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace DataModels.Models
{
/// <summary>
/// Интерфейс для сущности "Счет"
/// </summary>
public interface IOrderModel : IId
{
/// <summary>
/// ФИО официанта
/// </summary>
string WaiterFullName { get; }
/// <summary>
/// Путь до скана чека
/// </summary>
string PicturePath { get; }
/// <summary>
/// Заказанное блюдо
/// </summary>
string Dish { get; }
/// <summary>
/// Дата заказа
/// </summary>
DateTime OrderDate { get; }
}
}

View File

@ -0,0 +1,42 @@
using DatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement
{
public class Database : DbContext
{
/// <summary>
/// Параметры подключения к базе данных
/// </summary>
private string _dbConnectionString = "Host=localhost;Port=5432;Database=COPLabWorks;Username=postgres;Password=1111";
/// <summary>
/// Подключение к базе данных
/// </summary>
/// <param name="optionsBuilder"></param>
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseNpgsql(_dbConnectionString);
}
base.OnConfiguring(optionsBuilder);
}
/// <summary>
/// Таблица "Счета"
/// </summary>
public virtual DbSet<Order> Orders { get; set; }
/// <summary>
/// Таблица "Типы заказов"
/// </summary>
public virtual DbSet<Dish> Dishs { get; set; }
}
}

View File

@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.13">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Contracts\Contracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,126 @@
using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.StorageContracts;
using Contracts.ViewModels;
using DatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement.Implements
{
public class DishStorage : IDishStorage
{
/// <summary>
/// Получить полный список элементов
/// </summary>
/// <returns></returns>
public List<DishViewModel> GetFullList()
{
using var context = new Database();
return context.Dishs
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получить фильтрованный список элементов
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<DishViewModel> GetFilteredList(DishSearchModel model)
{
using var context = new Database();
// Фильтрация по названию типа
if (!string.IsNullOrEmpty(model.Name))
{
return context.Dishs
.Where(x => x.Name.Contains(model.Name))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
/// <summary>
/// Получить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DishViewModel? GetElement(DishSearchModel model)
{
using var context = new Database();
if (model.Id.HasValue)
{
return context.Dishs
.FirstOrDefault(x => x.Id.Equals(model.Id))
?.GetViewModel;
}
return null;
}
/// <summary>
/// Добавить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DishViewModel? Insert(DishBindingModel model)
{
using var context = new Database();
var newDish = Dish.Create(model);
if (newDish == null)
{
return null;
}
context.Dishs.Add(newDish);
context.SaveChanges();
return newDish.GetViewModel;
}
/// <summary>
/// Редактировать элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DishViewModel? Update(DishBindingModel model)
{
using var context = new Database();
var orderType = context.Dishs
.FirstOrDefault(x => x.Id.Equals(model.Id));
if (orderType == null)
{
return null;
}
orderType.Update(model);
context.SaveChanges();
return orderType.GetViewModel;
}
/// <summary>
/// Удалить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DishViewModel? Delete(DishBindingModel model)
{
using var context = new Database();
var orderType = context.Dishs
.FirstOrDefault(x => x.Id.Equals(model.Id));
if (orderType == null)
{
return null;
}
context.Dishs.Remove(orderType);
context.SaveChanges();
return orderType.GetViewModel;
}
}
}

View File

@ -0,0 +1,135 @@
using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.StorageContracts;
using Contracts.ViewModels;
using DatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
/// <summary>
/// Получить полный список элементов
/// </summary>
/// <returns></returns>
public List<OrderViewModel> GetFullList()
{
using var context = new Database();
return context.Orders
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получить фильтрованный список элементов
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
using var context = new Database();
// Фильтрация по ФИО официанта
if (!string.IsNullOrEmpty(model.WaiterFullName))
{
return context.Orders
.Where(x => x.WaiterFullName.Contains(model.WaiterFullName))
.Select(x => x.GetViewModel)
.ToList();
}
// Фильтрация по блюду
if (!string.IsNullOrEmpty(model.Dish))
{
return context.Orders
.Where(x => x.Dish.Contains(model.Dish))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
/// <summary>
/// Получить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public OrderViewModel? GetElement(OrderSearchModel model)
{
using var context = new Database();
if (model.Id.HasValue)
{
return context.Orders
.FirstOrDefault(x => x.Id.Equals(model.Id))
?.GetViewModel;
}
return null;
}
/// <summary>
/// Добавить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public OrderViewModel? Insert(OrderBindingModel model)
{
using var context = new Database();
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
context.Orders.Add(newOrder);
context.SaveChanges();
return newOrder.GetViewModel;
}
/// <summary>
/// Редактировать элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new Database();
var order = context.Orders
.FirstOrDefault(x => x.Id.Equals(model.Id));
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return order.GetViewModel;
}
/// <summary>
/// Удалить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new Database();
var order = context.Orders
.FirstOrDefault(x => x.Id.Equals(model.Id));
if (order == null)
{
return null;
}
context.Orders.Remove(order);
context.SaveChanges();
return order.GetViewModel;
}
}
}

View File

@ -0,0 +1,75 @@
// <auto-generated />
using System;
using DatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace DatabaseImplement.Migrations
{
[DbContext(typeof(Database))]
[Migration("20241004064731_init")]
partial class init
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.13")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("DatabaseImplement.Models.Dish", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Dishs");
});
modelBuilder.Entity("DatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Dish")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("OrderDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("PicturePath")
.IsRequired()
.HasColumnType("text");
b.Property<string>("WaiterFullName")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,55 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace DatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class init : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Dishs",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Dishs", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
WaiterFullName = table.Column<string>(type: "text", nullable: false),
PicturePath = table.Column<string>(type: "text", nullable: false),
Dish = table.Column<string>(type: "text", nullable: false),
OrderDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Dishs");
migrationBuilder.DropTable(
name: "Orders");
}
}
}

View File

@ -0,0 +1,72 @@
// <auto-generated />
using System;
using DatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace DatabaseImplement.Migrations
{
[DbContext(typeof(Database))]
partial class DatabaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.13")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("DatabaseImplement.Models.Dish", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Dishs");
});
modelBuilder.Entity("DatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Dish")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("OrderDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("PicturePath")
.IsRequired()
.HasColumnType("text");
b.Property<string>("WaiterFullName")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,67 @@
using Contracts.BindingModels;
using Contracts.ViewModels;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement.Models
{
public class Dish
{
public int Id { get; private set; }
[Required]
public string Name { get; private set; } = string.Empty;
public static Dish? Create(DishBindingModel model)
{
if (model == null)
{
return null;
}
return new Dish
{
Id = model.Id,
Name = model.Name,
};
}
public static Dish? Create(DishViewModel model)
{
if (model == null)
{
return null;
}
return new Dish
{
Id = model.Id,
Name = model.Name,
};
}
public void Update(DishBindingModel model)
{
if (model == null)
{
return;
}
Name = model.Name;
}
/// <summary>
/// Получить модель отображения
/// </summary>
public DishViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
};
}
}

View File

@ -0,0 +1,76 @@
using Contracts.BindingModels;
using Contracts.ViewModels;
using DataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement.Models
{
public class Order : IOrderModel
{
public int Id { get; private set; }
[Required]
public string WaiterFullName { get; private set; } = string.Empty;
[Required]
public string PicturePath { get; private set; } = string.Empty;
[Required]
public string Dish { get; private set; } = string.Empty;
[Required]
public DateTime OrderDate { get; private set; }
public static Order? Create(OrderBindingModel model)
{
if (model == null)
{
return null;
}
return new Order
{
Id = model.Id,
WaiterFullName = model.WaiterFullName,
PicturePath = model.PicturePath,
Dish = model.Dish,
OrderDate = model.OrderDate,
};
}
/// <summary>
/// Изменить модель
/// </summary>
/// <param name="model"></param>
public void Update(OrderBindingModel model)
{
if (model == null)
{
return;
}
WaiterFullName = model.WaiterFullName;
PicturePath = model.PicturePath;
Dish = model.Dish;
OrderDate = model.OrderDate;
}
/// <summary>
/// Получить модель отображения
/// </summary>
public OrderViewModel GetViewModel => new()
{
Id = Id,
WaiterFullName = WaiterFullName,
PicturePath = PicturePath,
Dish = Dish,
OrderDate = OrderDate,
};
}
}

View File

@ -1,133 +0,0 @@
namespace TestForm
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
userCheckedListBox1 = new Components.UserCheckedListBox();
userTextBox1 = new Components.Components.VisualComponents.UserTextBox();
userTreeView1 = new Components.Components.VisualComponents.UserTreeView();
pdfTable1 = new Components.Components.NonVisualComponents.PdfTable(components);
pdfPieChart1 = new Components.Components.NonVisualComponents.PdfPieChart(components);
pdfImage1 = new Components.Components.NonVisualComponents.PdfImage(components);
PdfImage = new Button();
PdfTable = new Button();
PdfChart = new Button();
openFileDialog1 = new OpenFileDialog();
SuspendLayout();
//
// userCheckedListBox1
//
userCheckedListBox1.Location = new Point(12, 163);
userCheckedListBox1.Name = "userCheckedListBox1";
userCheckedListBox1.SelectedElement = "";
userCheckedListBox1.Size = new Size(188, 188);
userCheckedListBox1.TabIndex = 0;
//
// userTextBox1
//
userTextBox1.Location = new Point(301, 12);
userTextBox1.MaxValue = null;
userTextBox1.MinValue = null;
userTextBox1.Name = "userTextBox1";
userTextBox1.Size = new Size(396, 76);
userTextBox1.TabIndex = 1;
//
// userTreeView1
//
userTreeView1.Location = new Point(225, 84);
userTreeView1.Name = "userTreeView1";
userTreeView1.SelectedNodeIndex = -1;
userTreeView1.Size = new Size(550, 329);
userTreeView1.TabIndex = 2;
//
// PdfImage
//
PdfImage.Location = new Point(31, 453);
PdfImage.Name = "PdfImage";
PdfImage.Size = new Size(201, 29);
PdfImage.TabIndex = 3;
PdfImage.Text = "Create PdfImage";
PdfImage.UseVisualStyleBackColor = true;
PdfImage.Click += PdfImage_Click;
//
// PdfTable
//
PdfTable.Location = new Point(263, 453);
PdfTable.Name = "PdfTable";
PdfTable.Size = new Size(201, 29);
PdfTable.TabIndex = 4;
PdfTable.Text = "Create PdfTable";
PdfTable.UseVisualStyleBackColor = true;
PdfTable.Click += PdfTable_Click;
//
// PdfChart
//
PdfChart.Location = new Point(501, 453);
PdfChart.Name = "PdfChart";
PdfChart.Size = new Size(180, 29);
PdfChart.TabIndex = 5;
PdfChart.Text = "Create PdfChart";
PdfChart.UseVisualStyleBackColor = true;
PdfChart.Click += PdfChart_Click;
//
// openFileDialog1
//
openFileDialog1.FileName = "openFileDialog1";
openFileDialog1.Multiselect = true;
//
// Form1
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1005, 490);
Controls.Add(PdfChart);
Controls.Add(PdfTable);
Controls.Add(PdfImage);
Controls.Add(userTreeView1);
Controls.Add(userTextBox1);
Controls.Add(userCheckedListBox1);
Name = "Form1";
Text = "Form1";
ResumeLayout(false);
}
#endregion
private Components.UserCheckedListBox userCheckedListBox1;
private Components.Components.VisualComponents.UserTextBox userTextBox1;
private Components.Components.VisualComponents.UserTreeView userTreeView1;
private Components.Components.NonVisualComponents.PdfTable pdfTable1;
private Components.Components.NonVisualComponents.PdfPieChart pdfPieChart1;
private Components.Components.NonVisualComponents.PdfImage pdfImage1;
private Button PdfImage;
private Button PdfTable;
private Button PdfChart;
private OpenFileDialog openFileDialog1;
}
}

View File

@ -1,101 +0,0 @@
using Components.Components.NonVisualComponents.HelperModels;
using Components.Components.VisualComponents.Classes;
using System.Windows.Forms;
using static System.Reflection.Metadata.BlobBuilder;
namespace TestForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
userCheckedListBox1.AddToList("Item 1");
userCheckedListBox1.AddToList("Item 2");
userCheckedListBox1.AddToList("Item 3");
userTextBox1.MinValue = 5;
userTextBox1.MaxValue = 15;
var hierarchy = new List<string> { "Race", "Class", "FullName" };
userTreeView1.SetHierarchy(hierarchy);
var characters = new List<Character>() {
new Character { Race = "Dwarf", Class = "Warrior", FullName = "Gimli" },
new Character { Race = "Elf", Class = "Archer", FullName = "Legolas" },
new Character { Race = "Human", Class = "Ranger", FullName = "Aragorn" },
new Character { Race = "Human", Class = "Paladin", FullName = "Boromir" }
};
foreach (var character in characters)
{
userTreeView1.AddObjectToTree(character);
}
}
private void PdfImage_Click(object sender, EventArgs e)
{
var res = openFileDialog1.ShowDialog(this);
if (res != DialogResult.OK) return;
var files = openFileDialog1.FileNames;
openFileDialog1.Dispose();
string path = "C:\\testImage.pdf";
MessageBox.Show(path);
if (pdfImage1.CreatePdfDoc(new DataForImage(path, "Images", files))) MessageBox.Show("Success!");
else MessageBox.Show("Error");
}
private void PdfTable_Click(object sender, EventArgs e)
{
List<CharacterInfo> charactersinfo = new List<CharacterInfo>()
{
new CharacterInfo("139", "Gimli", "Elf-friend", "4'9", "196 lbs"),
new CharacterInfo("2931", "Legolas", "Greenleaf", "6'0", "150 lbs"),
new CharacterInfo("87", "Aragorn", "Strider", "6'6", "210 lbs"),
new CharacterInfo("41", "Boromir", "Captain of Gondor", "6'4", "225 lbs")
};
List<(int, int)> merges = new List<(int, int)>();
merges.Add((2, 3));
List<int> heights = new List<int> { 10, 40, 60, 20, 25, 15, 20 };
string path = "C:\\testTable.pdf";
List<(string, string)> headers = new List<(string, string)>
{
("id", "Id"),
("Age", "Age"),
("", "Heroes of Middle-earth"),
("Name", "Name"),
("AKA", "AKA"),
("Height", "Height"),
("Weight", "Weight")
};
if (pdfTable1.createTable(new DataForTable<CharacterInfo>(path, "Table", heights, merges, headers, charactersinfo)))
{
MessageBox.Show("Success");
}
}
private void PdfChart_Click(object sender, EventArgs e)
{
string path = "C:\\testChart.pdf";
List<(double, string)> elements = new List<(double, string)>
{
(42, "Gimli"),
(41, "Legolas"),
(214, "Aragorn"),
(1, "Boromir")
};
if (pdfPieChart1.CreatePieChart(new DataForPieChart(path, "Title", "Pie chart", DiagramLegendEnum.Top, "Orcs killed", elements)))
{
MessageBox.Show("Success");
}
}
}
}

69
TestForm/FormDish.Designer.cs generated Normal file
View File

@ -0,0 +1,69 @@
using System.Windows.Forms;
namespace WinForms
{
partial class FormDish
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.BackgroundColor = SystemColors.Control;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(384, 211);
dataGridView.TabIndex = 0;
dataGridView.CellEndEdit += dataGridView_CellEndEdit;
dataGridView.KeyDown += dataGridView_KeyDown;
//
// FormDish
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(384, 211);
Controls.Add(dataGridView);
Name = "FormDish";
Text = "Блюда";
Load += FormDish_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
}
}

127
TestForm/FormDish.cs Normal file
View File

@ -0,0 +1,127 @@
using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinForms
{
public partial class FormDish : Form
{
private readonly IDishLogic _dishLogic;
private BindingList<DishBindingModel> _bindingList;
public FormDish(IDishLogic dishLogic)
{
InitializeComponent();
_dishLogic = dishLogic;
_bindingList = new BindingList<DishBindingModel>();
}
private void FormDish_Load(object sender, EventArgs e)
{
LoadData();
}
private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var typeName = dataGridView.CurrentRow.Cells[1].Value.ToString();
if (!string.IsNullOrEmpty(typeName))
{
int id = dataGridView.CurrentRow.Cells[0].Value != null
? Convert.ToInt32(dataGridView.CurrentRow.Cells[0].Value)
: 0;
string name = dataGridView.CurrentRow.Cells[1].EditedFormattedValue.ToString()!;
var model = new DishBindingModel
{
Id = id,
Name = name
};
var operatingResult = id != 0 ? _dishLogic.Update(model) : _dishLogic.Create(model);
if (!operatingResult)
{
throw new Exception("Ошибка при создании сущности 'Заказанное блюдо'!");
}
}
else
{
MessageBox.Show("Введена пустая строка!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
private void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Insert)
{
if (dataGridView.Rows.Count == 0)
{
_bindingList.Add(new DishBindingModel());
dataGridView.DataSource = new BindingList<DishBindingModel>(_bindingList);
dataGridView.CurrentCell = dataGridView.Rows[0].Cells[1];
return;
}
if (dataGridView.Rows[dataGridView.Rows.Count - 1].Cells[1].Value != null)
{
_bindingList.Add(new DishBindingModel());
dataGridView.DataSource = new BindingList<DishBindingModel>(_bindingList);
dataGridView.CurrentCell = dataGridView.Rows[dataGridView.Rows.Count - 1].Cells[1];
return;
}
}
if (e.KeyData == Keys.Delete)
{
if (MessageBox.Show("Удалить выбранный элемент?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_dishLogic.Delete(new DishBindingModel { Id = (int)dataGridView.CurrentRow.Cells[0].Value });
LoadData();
}
}
}
private void LoadData()
{
try
{
var types = _dishLogic.ReadList(null);
if (types == null)
{
return;
}
_bindingList.Clear();
foreach (var type in types)
{
_bindingList.Add(new DishBindingModel
{
Id = type.Id,
Name = type.Name,
});
}
if (_bindingList != null)
{
dataGridView.DataSource = _bindingList;
dataGridView.Columns[0].Visible = false;
dataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

120
TestForm/FormDish.resx Normal file
View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

157
TestForm/FormMain.Designer.cs generated Normal file
View File

@ -0,0 +1,157 @@
namespace WinForms
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
contextMenuStrip = new ContextMenuStrip(components);
заказToolStripMenuItem = new ToolStripMenuItem();
созToolStripMenuItem = new ToolStripMenuItem();
редактироватьToolStripMenuItem = new ToolStripMenuItem();
удалитьToolStripMenuItem = new ToolStripMenuItem();
блюдоToolStripMenuItem = new ToolStripMenuItem();
документыToolStripMenuItem = new ToolStripMenuItem();
wordToolStripMenuItem = new ToolStripMenuItem();
excelToolStripMenuItem = new ToolStripMenuItem();
pdfToolStripMenuItem = new ToolStripMenuItem();
tableComponent = new Components.NonVisualComponents.TableComponent(components);
pdfImage = new Components.Components.NonVisualComponents.PdfImage(components);
componentDocumentWithChartBarWord = new ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartBarWord(components);
controlDataListRow1 = new ControlsLibraryNet60.Data.ControlDataListRow();
contextMenuStrip.SuspendLayout();
SuspendLayout();
//
// contextMenuStrip
//
contextMenuStrip.ImageScalingSize = new Size(20, 20);
contextMenuStrip.Items.AddRange(new ToolStripItem[] { заказToolStripMenuItem, блюдоToolStripMenuItem, документыToolStripMenuItem });
contextMenuStrip.Name = "contextMenuStrip";
contextMenuStrip.Size = new Size(157, 76);
contextMenuStrip.Text = "Управление";
//
// заказToolStripMenuItem
//
заказToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { созToolStripMenuItem, редактироватьToolStripMenuItem, удалитьToolStripMenuItem });
заказToolStripMenuItem.Name = аказToolStripMenuItem";
заказToolStripMenuItem.Size = new Size(156, 24);
заказToolStripMenuItem.Text = "Заказ";
//
// созToolStripMenuItem
//
созToolStripMenuItem.Name = "созToolStripMenuItem";
созToolStripMenuItem.Size = new Size(194, 26);
созToolStripMenuItem.Text = "Создать";
созToolStripMenuItem.Click += созToolStripMenuItem_Click;
//
// редактироватьToolStripMenuItem
//
редактироватьToolStripMenuItem.Name = "редактироватьToolStripMenuItem";
редактироватьToolStripMenuItem.Size = new Size(194, 26);
редактироватьToolStripMenuItem.Text = "Редактировать";
редактироватьToolStripMenuItem.Click += редактироватьToolStripMenuItem_Click;
//
// удалитьToolStripMenuItem
//
удалитьToolStripMenuItem.Name = "удалитьToolStripMenuItem";
удалитьToolStripMenuItem.Size = new Size(194, 26);
удалитьToolStripMenuItem.Text = "Удалить";
удалитьToolStripMenuItem.Click += удалитьToolStripMenuItem_Click;
//
// блюдоToolStripMenuItem
//
блюдоToolStripMenuItem.Name = "блюдоToolStripMenuItem";
блюдоToolStripMenuItem.Size = new Size(156, 24);
блюдоToolStripMenuItem.Text = "Блюдо";
блюдоToolStripMenuItem.Click += блюдоToolStripMenuItem_Click;
//
// документыToolStripMenuItem
//
документыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { wordToolStripMenuItem, excelToolStripMenuItem, pdfToolStripMenuItem });
документыToolStripMenuItem.Name = окументыToolStripMenuItem";
документыToolStripMenuItem.Size = new Size(156, 24);
документыToolStripMenuItem.Text = "Документы";
//
// wordToolStripMenuItem
//
wordToolStripMenuItem.Name = "wordToolStripMenuItem";
wordToolStripMenuItem.Size = new Size(224, 26);
wordToolStripMenuItem.Text = "Word";
wordToolStripMenuItem.Click += wordToolStripMenuItem_Click;
//
// excelToolStripMenuItem
//
excelToolStripMenuItem.Name = "excelToolStripMenuItem";
excelToolStripMenuItem.Size = new Size(224, 26);
excelToolStripMenuItem.Text = "Excel";
excelToolStripMenuItem.Click += excelToolStripMenuItem_Click;
//
// pdfToolStripMenuItem
//
pdfToolStripMenuItem.Name = "pdfToolStripMenuItem";
pdfToolStripMenuItem.Size = new Size(224, 26);
pdfToolStripMenuItem.Text = "Pdf";
pdfToolStripMenuItem.Click += pdfToolStripMenuItem_Click;
//
// controlDataListRow1
//
controlDataListRow1.Location = new Point(-4, -2);
controlDataListRow1.Margin = new Padding(4, 5, 4, 5);
controlDataListRow1.Name = "controlDataListRow1";
controlDataListRow1.SelectedRowIndex = -1;
controlDataListRow1.Size = new Size(808, 432);
controlDataListRow1.TabIndex = 1;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 426);
Controls.Add(controlDataListRow1);
Name = "FormMain";
Text = "FormMain";
contextMenuStrip.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private ContextMenuStrip contextMenuStrip;
private ToolStripMenuItem заказToolStripMenuItem;
private ToolStripMenuItem созToolStripMenuItem;
private ToolStripMenuItem редактироватьToolStripMenuItem;
private ToolStripMenuItem удалитьToolStripMenuItem;
private ToolStripMenuItem блюдоToolStripMenuItem;
private ToolStripMenuItem документыToolStripMenuItem;
private ToolStripMenuItem wordToolStripMenuItem;
private ToolStripMenuItem excelToolStripMenuItem;
private ToolStripMenuItem pdfToolStripMenuItem;
private Components.NonVisualComponents.TableComponent tableComponent;
private Components.Components.NonVisualComponents.PdfImage pdfImage;
private ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartBarWord componentDocumentWithChartBarWord;
private ControlsLibraryNet60.Data.ControlDataListRow controlDataListRow1;
}
}

334
TestForm/FormMain.cs Normal file
View File

@ -0,0 +1,334 @@
using Components.Components.NonVisualComponents.HelperModels;
using Components.Components.VisualComponents;
using Components.NonVisualComponents;
using Components.NonVisualComponents.HelperModels;
using ComponentsLibraryNet60.Models;
using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using Contracts.ViewModels;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MergeCells = Components.NonVisualComponents.HelperModels.MergeCells;
namespace WinForms
{
public partial class FormMain : Form
{
private readonly IOrderLogic _orderLogic;
private readonly IDishLogic _dishLogic;
public FormMain(IDishLogic dishLogic, IOrderLogic orderLogic)
{
_dishLogic = dishLogic;
_orderLogic = orderLogic;
InitializeComponent();
controlDataListRow1.ContextMenuStrip = contextMenuStrip;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var orders = _orderLogic.ReadList(null);
if (orders == null)
{
return;
}
foreach (var order in orders)
{
controlDataListRow1.AddRow(order);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AddElement()
{
var service = Program.ServiceProvider?.GetService(typeof(FormOrder));
if (!(service is FormOrder form))
{
return;
}
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
private void UpdateElement()
{
var service = Program.ServiceProvider?.GetService(typeof(FormOrder));
if (!(service is FormOrder form))
{
return;
}
var selectedOrder = controlDataListRow1.GetSelectedObject<OrderViewModel>();
if (selectedOrder == null)
{
MessageBox.Show("Выберите счет для редактирования!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
form.Id = Convert.ToInt32(selectedOrder.Id);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
private void DeleteElement()
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
var selectedOrder = controlDataListRow1.GetSelectedObject<OrderViewModel>();
int id = Convert.ToInt32(selectedOrder.Id);
try
{
_orderLogic.Delete(new OrderBindingModel { Id = id });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
private void CreatePdf()
{
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Файл выбран", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else return;
}
List<string> images = new List<string>();
var list = _orderLogic.ReadList(null);
try
{
if (list != null)
{
foreach (var item in list)
{
images.Add(item.PicturePath);
}
string[] imagesArray = images.ToArray();
pdfImage.CreatePdfDoc(new DataForImage(fileName, "Сканы чеков", imagesArray));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка");
}
}
private void CreateExcel()
{
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Файл выбран", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else return;
}
string title = "Документ с таблицей";
List<MergeCells> mergeCells = new List<MergeCells>()
{
new MergeCells("Счет", new int[] { 2, 3})
};
List<ColumnInfo> columns = new List<ColumnInfo>()
{
new ColumnInfo("Id", "Идент.", 10),
new ColumnInfo("WaiterFullName", "Статус", 10),
new ColumnInfo("Dish", "Блюдо", 20),
new ColumnInfo("OrderDate", "Дата оплаты чека", 30),
};
var list = _orderLogic.ReadList(null);
try
{
tableComponent.CreateDocument(fileName, title,
mergeCells, columns,
list);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка");
}
}
private void CreateWord()
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "docx|*.docx" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Файл выбран", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else return;
}
var items = new Dictionary<string, List<(int Date, double Value)>>();
var list_order = _orderLogic.ReadList(null);
var list_dish = _dishLogic.ReadList(null);
foreach (var dish in list_dish)
{
int count = 0;
foreach (var o in list_order)
if (o.Dish.Contains(dish.Name)) count++;
items.Add(dish.Name, new List<(int Date, double Value)> { (0, count) });
}
try
{
componentDocumentWithChartBarWord.CreateDoc(new ComponentDocumentWithChartConfig
{
FilePath = fileName,
ChartTitle = "Количество заказов определенных блюд",
Data = items
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка");
}
}
private void созToolStripMenuItem_Click(object sender, EventArgs e)
{
AddElement();
}
private void редактироватьToolStripMenuItem_Click(object sender, EventArgs e)
{
UpdateElement();
}
private void удалитьToolStripMenuItem_Click(object sender, EventArgs e)
{
DeleteElement();
}
private void wordToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateWord();
}
private void excelToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateExcel();
}
private void pdfToolStripMenuItem_Click(object sender, EventArgs e)
{
CreatePdf();
}
private void ShowFormDish()
{
var service = Program.ServiceProvider?.GetService(typeof(FormDish));
if (!(service is FormDish form))
{
return;
}
form.ShowDialog();
}
private void блюдоToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowFormDish();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// Ctrl+A - добавить запись
if (keyData == (Keys.Control | Keys.A))
{
AddElement();
return true;
}
// Ctrl+U - редактировать запись
if (keyData == (Keys.Control | Keys.U))
{
UpdateElement();
return true;
}
// Ctrl+D - удалить запись
if (keyData == (Keys.Control | Keys.D))
{
DeleteElement();
return true;
}
// Ctrl+S - создать документ Word
if (keyData == (Keys.Control | Keys.S))
{
CreateWord();
return true;
}
// Ctrl+T - создать документ Excel
if (keyData == (Keys.Control | Keys.T))
{
CreateExcel();
return true;
}
// Ctrl+C - создать документ Pdf
if (keyData == (Keys.Control | Keys.C))
{
CreatePdf();
return true;
}
// Ctrl+M - вывести форму списка блюд
if (keyData == (Keys.Control | Keys.M))
{
ShowFormDish();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
}

View File

@ -117,16 +117,16 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="pdfTable1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<metadata name="contextMenuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="pdfPieChart1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>139, 17</value>
<metadata name="tableComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>194, 17</value>
</metadata>
<metadata name="pdfImage1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>281, 17</value>
<metadata name="pdfImage.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>362, 17</value>
</metadata>
<metadata name="openFileDialog1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>410, 17</value>
<metadata name="componentDocumentWithChartBarWord.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>483, 17</value>
</metadata>
</root>

157
TestForm/FormOrder.Designer.cs generated Normal file
View File

@ -0,0 +1,157 @@
namespace WinForms
{
partial class FormOrder
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
textBoxWaiterFullName = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
label1 = new Label();
labelDish = new Label();
customTextBox1 = new Components.VisualComponents.CustomTextBox();
textBoxScan = new TextBox();
label2 = new Label();
controlSelectedListBoxSingle = new ControlsLibraryNet60.Selected.ControlSelectedListBoxSingle();
SuspendLayout();
//
// textBoxWaiterFullName
//
textBoxWaiterFullName.Location = new Point(13, 33);
textBoxWaiterFullName.Margin = new Padding(3, 4, 3, 4);
textBoxWaiterFullName.Name = "textBoxWaiterFullName";
textBoxWaiterFullName.Size = new Size(250, 27);
textBoxWaiterFullName.TabIndex = 0;
//
// buttonSave
//
buttonSave.Location = new Point(13, 545);
buttonSave.Margin = new Padding(3, 4, 3, 4);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(114, 31);
buttonSave.TabIndex = 1;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
//
// buttonCancel
//
buttonCancel.Location = new Point(177, 545);
buttonCancel.Margin = new Padding(3, 4, 3, 4);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(86, 31);
buttonCancel.TabIndex = 2;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(13, 9);
label1.Name = "label1";
label1.Size = new Size(129, 20);
label1.TabIndex = 6;
label1.Text = "ФИО официанта*";
//
// labelDish
//
labelDish.AutoSize = true;
labelDish.Location = new Point(13, 117);
labelDish.Name = "labelDish";
labelDish.Size = new Size(146, 20);
labelDish.TabIndex = 7;
labelDish.Text = "Заказанное блюдо*";
//
// customTextBox1
//
customTextBox1.DatePattern = null;
customTextBox1.Location = new Point(13, 401);
customTextBox1.Margin = new Padding(3, 4, 3, 4);
customTextBox1.Name = "customTextBox1";
customTextBox1.Size = new Size(242, 89);
customTextBox1.TabIndex = 9;
//
// textBoxScan
//
textBoxScan.Location = new Point(13, 87);
textBoxScan.Name = "textBoxScan";
textBoxScan.Size = new Size(125, 27);
textBoxScan.TabIndex = 10;
textBoxScan.Text = "Нажми сюда";
textBoxScan.Click += textBoxScan_Click;
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(13, 64);
label2.Name = "label2";
label2.Size = new Size(77, 20);
label2.TabIndex = 12;
label2.Text = "Скан чека";
//
// controlSelectedListBoxSingle
//
controlSelectedListBoxSingle.Location = new Point(13, 142);
controlSelectedListBoxSingle.Margin = new Padding(4, 5, 4, 5);
controlSelectedListBoxSingle.Name = "controlSelectedListBoxSingle";
controlSelectedListBoxSingle.SelectedElement = "";
controlSelectedListBoxSingle.Size = new Size(250, 233);
controlSelectedListBoxSingle.TabIndex = 13;
//
// FormOrder
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(275, 589);
Controls.Add(controlSelectedListBoxSingle);
Controls.Add(label2);
Controls.Add(textBoxScan);
Controls.Add(customTextBox1);
Controls.Add(labelDish);
Controls.Add(label1);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxWaiterFullName);
Margin = new Padding(3, 4, 3, 4);
Name = "FormOrder";
Text = "Счет";
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBoxWaiterFullName;
private Button buttonSave;
private Button buttonCancel;
private Label label1;
private Label labelDish;
private Components.VisualComponents.CustomTextBox customTextBox1;
private TextBox textBoxScan;
private Label label2;
private ControlsLibraryNet60.Selected.ControlSelectedListBoxSingle controlSelectedListBoxSingle;
}
}

156
TestForm/FormOrder.cs Normal file
View File

@ -0,0 +1,156 @@
using Components.VisualComponents;
using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using Contracts.SearchModels;
using ControlsLibraryNet60.Input;
using DocumentFormat.OpenXml.Office2010.Word.DrawingShape;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinForms
{
public partial class FormOrder : Form
{
private readonly IOrderLogic _orderLogic;
private readonly IDishLogic _dishLogic;
private int? _id;
public int Id { set { _id = value; } }
public FormOrder(IOrderLogic orderLogic, IDishLogic dishLogic)
{
InitializeComponent();
_orderLogic = orderLogic;
_dishLogic = dishLogic;
}
/// <summary>
/// Загрузка формы
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormOrder_Load(object sender, EventArgs e)
{
var listDish = _dishLogic.ReadList(null);
if (listDish != null)
{
foreach (var type in listDish)
{
controlSelectedListBoxSingle.AddElement(type.Name);
}
}
if (!_id.HasValue)
{
return;
}
try
{
var order = _orderLogic.ReadElement(new OrderSearchModel { Id = _id.Value });
if (order == null)
{
return;
}
textBoxWaiterFullName.Text = order.WaiterFullName;
controlSelectedListBoxSingle.SelectedElement = order.Dish;
textBoxScan.Text = order.PicturePath;
customTextBox1.TextBoxValue = order.OrderDate.ToString("dd MMMM yyyy", CultureInfo.CreateSpecificCulture("ru-RU"));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Кнопка "Сохранить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxWaiterFullName.Text))
{
MessageBox.Show("Заполните ФИО официанта!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxScan.Text))
{
MessageBox.Show("Приложите скан чека!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(controlSelectedListBoxSingle.SelectedElement))
{
MessageBox.Show("Выберите блюдо!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(customTextBox1.TextBoxValue))
{
MessageBox.Show("Введите дату заказа!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
var model = new OrderBindingModel
{
Id = _id ?? 0,
WaiterFullName = textBoxWaiterFullName.Text,
Dish = controlSelectedListBoxSingle.SelectedElement,
PicturePath = textBoxScan.Text,
OrderDate = DateTime.Parse(customTextBox1.TextBoxValue),
};
var operatingResult = _id.HasValue ? _orderLogic.Update(model) : _orderLogic.Create(model);
if (!operatingResult)
{
throw new Exception("Ошибка при создании сущности 'Счет'!");
}
MessageBox.Show("Создание сущности 'Счет' прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Кнопка "Отмена"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void textBoxScan_Click(object sender, EventArgs e)
{
using (var dialog = new OpenFileDialog { Filter = "jpg|*.jpg" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
textBoxScan.Text = dialog.FileName.ToString();
}
}
}
}
}

120
TestForm/FormOrder.resx Normal file
View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -1,7 +1,23 @@
using BusinessLogics.BusinessLogics;
using Contracts.BusinessLogicsContracts;
using Contracts.StorageContracts;
using DatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using WinForms;
namespace TestForm
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
/// <summary>
/// IoC-êîíòåéíåð
/// </summary>
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
@ -11,7 +27,38 @@ namespace TestForm
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñîâ
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
// Ëîããåð
services.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
// IoC-êîíòåéíåð, õðàíèëèùà
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IDishStorage, DishStorage>();
// IoC-êîíòåéíåð, áèçíåñ-ëîãèêà
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IDishLogic, DishLogic>();
// IoC-êîíòåéíåð, ôîðìû îòîáðàæåíèÿ
services.AddTransient<FormMain>();
services.AddTransient<FormOrder>();
services.AddTransient<FormDish>();
}
}
}

View File

@ -1,15 +1,46 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="nlog.config" />
</ItemGroup>
<ItemGroup>
<Content Include="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="ComponentsLibraryNet60" Version="1.0.0" />
<PackageReference Include="ControlsLibraryNet60" Version="1.0.0" />
<PackageReference Include="CustomComponents" Version="1.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.13">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.14" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BusinessLogics\BusinessLogics.csproj" />
<ProjectReference Include="..\Components\Components.csproj" />
<ProjectReference Include="..\Contracts\Contracts.csproj" />
<ProjectReference Include="..\DatabaseImplement\DatabaseImplement.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="packages\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Components\Components.csproj" />
</ItemGroup>
</Project>

15
TestForm/nlog.config Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="log-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minLevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

69
WinForms/FormDish.Designer.cs generated Normal file
View File

@ -0,0 +1,69 @@
using System.Windows.Forms;
namespace WinForms
{
partial class FormDish
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.BackgroundColor = SystemColors.Control;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(384, 211);
dataGridView.TabIndex = 0;
dataGridView.CellEndEdit += dataGridView_CellEndEdit;
dataGridView.KeyDown += dataGridView_KeyDown;
//
// FormDish
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(384, 211);
Controls.Add(dataGridView);
Name = "FormDish";
Text = "Блюда";
Load += FormDish_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
}
}

127
WinForms/FormDish.cs Normal file
View File

@ -0,0 +1,127 @@
using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinForms
{
public partial class FormDish : Form
{
private readonly IDishLogic _dishLogic;
private BindingList<DishBindingModel> _bindingList;
public FormDish(IDishLogic dishLogic)
{
InitializeComponent();
_dishLogic = dishLogic;
_bindingList = new BindingList<DishBindingModel>();
}
private void FormDish_Load(object sender, EventArgs e)
{
LoadData();
}
private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var typeName = dataGridView.CurrentRow.Cells[1].Value.ToString();
if (!string.IsNullOrEmpty(typeName))
{
int id = dataGridView.CurrentRow.Cells[0].Value != null
? Convert.ToInt32(dataGridView.CurrentRow.Cells[0].Value)
: 0;
string name = dataGridView.CurrentRow.Cells[1].EditedFormattedValue.ToString()!;
var model = new DishBindingModel
{
Id = id,
Name = name
};
var operatingResult = id != 0 ? _dishLogic.Update(model) : _dishLogic.Create(model);
if (!operatingResult)
{
throw new Exception("Ошибка при создании сущности 'Заказанное блюдо'!");
}
}
else
{
MessageBox.Show("Введена пустая строка!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
private void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Insert)
{
if (dataGridView.Rows.Count == 0)
{
_bindingList.Add(new DishBindingModel());
dataGridView.DataSource = new BindingList<DishBindingModel>(_bindingList);
dataGridView.CurrentCell = dataGridView.Rows[0].Cells[1];
return;
}
if (dataGridView.Rows[dataGridView.Rows.Count - 1].Cells[1].Value != null)
{
_bindingList.Add(new DishBindingModel());
dataGridView.DataSource = new BindingList<DishBindingModel>(_bindingList);
dataGridView.CurrentCell = dataGridView.Rows[dataGridView.Rows.Count - 1].Cells[1];
return;
}
}
if (e.KeyData == Keys.Delete)
{
if (MessageBox.Show("Удалить выбранный элемент?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_dishLogic.Delete(new DishBindingModel { Id = (int)dataGridView.CurrentRow.Cells[0].Value });
LoadData();
}
}
}
private void LoadData()
{
try
{
var types = _dishLogic.ReadList(null);
if (types == null)
{
return;
}
_bindingList.Clear();
foreach (var type in types)
{
_bindingList.Add(new DishBindingModel
{
Id = type.Id,
Name = type.Name,
});
}
if (_bindingList != null)
{
dataGridView.DataSource = _bindingList;
dataGridView.Columns[0].Visible = false;
dataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

120
WinForms/FormDish.resx Normal file
View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

159
WinForms/FormMain.Designer.cs generated Normal file
View File

@ -0,0 +1,159 @@
namespace WinForms
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
contextMenuStrip = new ContextMenuStrip(components);
заказToolStripMenuItem = new ToolStripMenuItem();
созToolStripMenuItem = new ToolStripMenuItem();
редактироватьToolStripMenuItem = new ToolStripMenuItem();
удалитьToolStripMenuItem = new ToolStripMenuItem();
блюдоToolStripMenuItem = new ToolStripMenuItem();
документыToolStripMenuItem = new ToolStripMenuItem();
wordToolStripMenuItem = new ToolStripMenuItem();
excelToolStripMenuItem = new ToolStripMenuItem();
pdfToolStripMenuItem = new ToolStripMenuItem();
tableComponent = new Components.NonVisualComponents.TableComponent(components);
pdfImage = new Components.Components.NonVisualComponents.PdfImage(components);
componentDocumentWithChartBarWord = new ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartBarWord(components);
controlDataTableRow1 = new ControlsLibraryNet60.Data.ControlDataTableRow();
contextMenuStrip.SuspendLayout();
SuspendLayout();
//
// contextMenuStrip
//
contextMenuStrip.ImageScalingSize = new Size(20, 20);
contextMenuStrip.Items.AddRange(new ToolStripItem[] { заказToolStripMenuItem, блюдоToolStripMenuItem, документыToolStripMenuItem });
contextMenuStrip.Name = "contextMenuStrip";
contextMenuStrip.Size = new Size(157, 76);
contextMenuStrip.Text = "Управление";
//
// заказToolStripMenuItem
//
заказToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { созToolStripMenuItem, редактироватьToolStripMenuItem, удалитьToolStripMenuItem });
заказToolStripMenuItem.Name = аказToolStripMenuItem";
заказToolStripMenuItem.Size = new Size(156, 24);
заказToolStripMenuItem.Text = "Заказ";
//
// созToolStripMenuItem
//
созToolStripMenuItem.Name = "созToolStripMenuItem";
созToolStripMenuItem.Size = new Size(194, 26);
созToolStripMenuItem.Text = "Создать";
созToolStripMenuItem.Click += созToolStripMenuItem_Click;
//
// редактироватьToolStripMenuItem
//
редактироватьToolStripMenuItem.Name = "редактироватьToolStripMenuItem";
редактироватьToolStripMenuItem.Size = new Size(194, 26);
редактироватьToolStripMenuItem.Text = "Редактировать";
редактироватьToolStripMenuItem.Click += редактироватьToolStripMenuItem_Click;
//
// удалитьToolStripMenuItem
//
удалитьToolStripMenuItem.Name = "удалитьToolStripMenuItem";
удалитьToolStripMenuItem.Size = new Size(194, 26);
удалитьToolStripMenuItem.Text = "Удалить";
удалитьToolStripMenuItem.Click += удалитьToolStripMenuItem_Click;
//
// блюдоToolStripMenuItem
//
блюдоToolStripMenuItem.Name = "блюдоToolStripMenuItem";
блюдоToolStripMenuItem.Size = new Size(156, 24);
блюдоToolStripMenuItem.Text = "Блюдо";
блюдоToolStripMenuItem.Click += блюдоToolStripMenuItem_Click;
//
// документыToolStripMenuItem
//
документыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { wordToolStripMenuItem, excelToolStripMenuItem, pdfToolStripMenuItem });
документыToolStripMenuItem.Name = окументыToolStripMenuItem";
документыToolStripMenuItem.Size = new Size(156, 24);
документыToolStripMenuItem.Text = "Документы";
//
// wordToolStripMenuItem
//
wordToolStripMenuItem.Name = "wordToolStripMenuItem";
wordToolStripMenuItem.Size = new Size(128, 26);
wordToolStripMenuItem.Text = "Word";
wordToolStripMenuItem.Click += wordToolStripMenuItem_Click;
//
// excelToolStripMenuItem
//
excelToolStripMenuItem.Name = "excelToolStripMenuItem";
excelToolStripMenuItem.Size = new Size(128, 26);
excelToolStripMenuItem.Text = "Excel";
excelToolStripMenuItem.Click += excelToolStripMenuItem_Click;
//
// pdfToolStripMenuItem
//
pdfToolStripMenuItem.Name = "pdfToolStripMenuItem";
pdfToolStripMenuItem.Size = new Size(128, 26);
pdfToolStripMenuItem.Text = "Pdf";
pdfToolStripMenuItem.Click += pdfToolStripMenuItem_Click;
//
// controlDataTableRow1
//
controlDataTableRow1.Dock = DockStyle.Fill;
controlDataTableRow1.Location = new Point(0, 0);
controlDataTableRow1.Margin = new Padding(4, 5, 4, 5);
controlDataTableRow1.Name = "controlDataTableRow1";
controlDataTableRow1.SelectedRowIndex = -1;
controlDataTableRow1.Size = new Size(800, 426);
controlDataTableRow1.TabIndex = 1;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 426);
Controls.Add(controlDataTableRow1);
Name = "FormMain";
Text = "FormMain";
Load += FormMain_Load;
contextMenuStrip.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private ContextMenuStrip contextMenuStrip;
private ToolStripMenuItem заказToolStripMenuItem;
private ToolStripMenuItem созToolStripMenuItem;
private ToolStripMenuItem редактироватьToolStripMenuItem;
private ToolStripMenuItem удалитьToolStripMenuItem;
private ToolStripMenuItem блюдоToolStripMenuItem;
private ToolStripMenuItem документыToolStripMenuItem;
private ToolStripMenuItem wordToolStripMenuItem;
private ToolStripMenuItem excelToolStripMenuItem;
private ToolStripMenuItem pdfToolStripMenuItem;
private Components.NonVisualComponents.TableComponent tableComponent;
private Components.Components.NonVisualComponents.PdfImage pdfImage;
private ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartBarWord componentDocumentWithChartBarWord;
private ControlsLibraryNet60.Data.ControlDataTableRow controlDataTableRow1;
}
}

386
WinForms/FormMain.cs Normal file
View File

@ -0,0 +1,386 @@
using BusinessLogics.BusinessLogics;
using Components.Components.NonVisualComponents.HelperModels;
using Components.Components.VisualComponents;
using Components.NonVisualComponents;
using Components.NonVisualComponents.HelperModels;
using ComponentsLibraryNet60.DocumentWithChart;
using ComponentsLibraryNet60.Models;
using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using Contracts.ViewModels;
using ControlsLibraryNet60.Models;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MergeCells = Components.NonVisualComponents.HelperModels.MergeCells;
namespace WinForms
{
public partial class FormMain : Form
{
private readonly IOrderLogic _orderLogic;
private readonly IDishLogic _dishLogic;
public FormMain(IDishLogic dishLogic, IOrderLogic orderLogic)
{
_dishLogic = dishLogic;
_orderLogic = orderLogic;
InitializeComponent();
List<DataTableColumnConfig> columnConfigs = new List<DataTableColumnConfig>
{
new DataTableColumnConfig
{
ColumnHeader = "Идентификатор",
PropertyName = "Id",
Width = 150,
Visible = true
},
new DataTableColumnConfig
{
ColumnHeader = "ФИО официанта",
PropertyName = "WaiterFullName",
Width = 250,
Visible = true
},
new DataTableColumnConfig
{
ColumnHeader = "Заказанное блюдо",
PropertyName = "Dish",
Width = 200,
Visible = true
},
new DataTableColumnConfig
{
ColumnHeader = "Дата оплаты счета",
PropertyName = "OrderDate",
Width = 200,
Visible = true
}
};
controlDataTableRow1.LoadColumns(columnConfigs);
controlDataTableRow1.ContextMenuStrip = contextMenuStrip;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
controlDataTableRow1.Clear();
try
{
var orders = _orderLogic.ReadList(null);
if (orders == null)
{
return;
}
foreach (var order in orders)
{
controlDataTableRow1.AddRow(order);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AddElement()
{
var service = Program.ServiceProvider?.GetService(typeof(FormOrder));
if (!(service is FormOrder form))
{
return;
}
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
private void UpdateElement()
{
var service = Program.ServiceProvider?.GetService(typeof(FormOrder));
if (!(service is FormOrder form))
{
return;
}
var selectedOrder = controlDataTableRow1.GetSelectedObject<OrderViewModel>();
if (selectedOrder == null)
{
MessageBox.Show("Выберите счет для редактирования!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
form.Id = Convert.ToInt32(selectedOrder.Id);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
private void DeleteElement()
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
var selectedOrder = controlDataTableRow1.GetSelectedObject<OrderViewModel>();
int id = Convert.ToInt32(selectedOrder.Id);
try
{
_orderLogic.Delete(new OrderBindingModel { Id = id });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
private void CreatePdf()
{
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Файл выбран", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else return;
}
List<string> images = new List<string>();
var list = _orderLogic.ReadList(null);
try
{
if (list != null)
{
foreach (var item in list)
{
images.Add(item.PicturePath);
}
string[] imagesArray = images.ToArray();
pdfImage.CreatePdfDoc(new DataForImage(fileName, "Сканы чеков", imagesArray));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка");
}
}
private void CreateExcel()
{
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Файл выбран", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else return;
}
string title = "Документ с таблицей";
List<MergeCells> mergeCells = new List<MergeCells>()
{
new MergeCells("Счет", new int[] { 1, 2})
};
List<ColumnInfo> columns = new List<ColumnInfo>()
{
new ColumnInfo("Id", "Идент.", 10),
new ColumnInfo("WaiterFullName", "ФИО официанта", 20),
new ColumnInfo("Dish", "Блюдо", 20),
new ColumnInfo("OrderDate", "Дата оплаты чека", 30),
new ColumnInfo("", "заглушка", 0),
};
var list = _orderLogic.ReadList(null);
try
{
tableComponent.CreateDocument(fileName, title,
mergeCells, columns,
list);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка");
}
}
private void CreateWord()
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "docx|*.docx" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Файл выбран", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else return;
}
var data = new Dictionary<string, List<(int Date, double Value)>>();
var orders = _orderLogic.ReadList(null);
var groupedOrders = orders.GroupBy(order => order.Dish)
.Select(group => new
{
DishName = group.Key,
OrderCount = group.Count()
})
.ToList();
data["Блюда"] = new List<(int Date, double Value)>();
int counter = 1;
foreach (var group in groupedOrders)
{
data["Блюда"].Add((counter, group.OrderCount));
counter++;
}
try
{
componentDocumentWithChartBarWord.CreateDoc(new ComponentDocumentWithChartConfig
{
Header = "test",
FilePath = fileName,
ChartTitle = "Количество заказов определенных блюд",
LegendLocation = ComponentsLibraryNet60.Models.Location.Bottom,
Data = data
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка");
}
}
private void созToolStripMenuItem_Click(object sender, EventArgs e)
{
AddElement();
}
private void редактироватьToolStripMenuItem_Click(object sender, EventArgs e)
{
UpdateElement();
}
private void удалитьToolStripMenuItem_Click(object sender, EventArgs e)
{
DeleteElement();
}
private void wordToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateWord();
}
private void excelToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateExcel();
}
private void pdfToolStripMenuItem_Click(object sender, EventArgs e)
{
CreatePdf();
}
private void ShowFormDish()
{
var service = Program.ServiceProvider?.GetService(typeof(FormDish));
if (!(service is FormDish form))
{
return;
}
form.ShowDialog();
}
private void блюдоToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowFormDish();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// Ctrl+A - добавить запись
if (keyData == (Keys.Control | Keys.A))
{
AddElement();
return true;
}
// Ctrl+U - редактировать запись
if (keyData == (Keys.Control | Keys.U))
{
UpdateElement();
return true;
}
// Ctrl+D - удалить запись
if (keyData == (Keys.Control | Keys.D))
{
DeleteElement();
return true;
}
// Ctrl+S - создать документ Word
if (keyData == (Keys.Control | Keys.S))
{
CreateWord();
return true;
}
// Ctrl+T - создать документ Excel
if (keyData == (Keys.Control | Keys.T))
{
CreateExcel();
return true;
}
// Ctrl+C - создать документ Pdf
if (keyData == (Keys.Control | Keys.C))
{
CreatePdf();
return true;
}
// Ctrl+M - вывести форму списка блюд
if (keyData == (Keys.Control | Keys.M))
{
ShowFormDish();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
}

135
WinForms/FormMain.resx Normal file
View File

@ -0,0 +1,135 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="contextMenuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="tableComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>194, 17</value>
</metadata>
<metadata name="pdfImage.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>362, 17</value>
</metadata>
<metadata name="componentDocumentWithChartBarWord.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>483, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>67</value>
</metadata>
</root>

160
WinForms/FormOrder.Designer.cs generated Normal file
View File

@ -0,0 +1,160 @@
namespace WinForms
{
partial class FormOrder
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
textBoxWaiterFullName = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
label1 = new Label();
labelDish = new Label();
customTextBox1 = new Components.VisualComponents.CustomTextBox();
textBoxScan = new TextBox();
label2 = new Label();
controlSelectedListBoxSingle = new ControlsLibraryNet60.Selected.ControlSelectedListBoxSingle();
SuspendLayout();
//
// textBoxWaiterFullName
//
textBoxWaiterFullName.Location = new Point(13, 33);
textBoxWaiterFullName.Margin = new Padding(3, 4, 3, 4);
textBoxWaiterFullName.Name = "textBoxWaiterFullName";
textBoxWaiterFullName.Size = new Size(250, 27);
textBoxWaiterFullName.TabIndex = 0;
//
// buttonSave
//
buttonSave.Location = new Point(13, 545);
buttonSave.Margin = new Padding(3, 4, 3, 4);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(114, 31);
buttonSave.TabIndex = 1;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(177, 545);
buttonCancel.Margin = new Padding(3, 4, 3, 4);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(86, 31);
buttonCancel.TabIndex = 2;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(13, 9);
label1.Name = "label1";
label1.Size = new Size(129, 20);
label1.TabIndex = 6;
label1.Text = "ФИО официанта*";
//
// labelDish
//
labelDish.AutoSize = true;
labelDish.Location = new Point(13, 117);
labelDish.Name = "labelDish";
labelDish.Size = new Size(146, 20);
labelDish.TabIndex = 7;
labelDish.Text = "Заказанное блюдо*";
//
// customTextBox1
//
customTextBox1.DatePattern = null;
customTextBox1.Location = new Point(13, 401);
customTextBox1.Margin = new Padding(3, 4, 3, 4);
customTextBox1.Name = "customTextBox1";
customTextBox1.Size = new Size(242, 89);
customTextBox1.TabIndex = 9;
//
// textBoxScan
//
textBoxScan.Location = new Point(13, 87);
textBoxScan.Name = "textBoxScan";
textBoxScan.Size = new Size(125, 27);
textBoxScan.TabIndex = 10;
textBoxScan.Text = "Нажми сюда";
textBoxScan.Click += textBoxScan_Click;
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(13, 64);
label2.Name = "label2";
label2.Size = new Size(77, 20);
label2.TabIndex = 12;
label2.Text = "Скан чека";
//
// controlSelectedListBoxSingle
//
controlSelectedListBoxSingle.Location = new Point(13, 142);
controlSelectedListBoxSingle.Margin = new Padding(4, 5, 4, 5);
controlSelectedListBoxSingle.Name = "controlSelectedListBoxSingle";
controlSelectedListBoxSingle.SelectedElement = "";
controlSelectedListBoxSingle.Size = new Size(250, 233);
controlSelectedListBoxSingle.TabIndex = 13;
//
// FormOrder
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(275, 589);
Controls.Add(controlSelectedListBoxSingle);
Controls.Add(label2);
Controls.Add(textBoxScan);
Controls.Add(customTextBox1);
Controls.Add(labelDish);
Controls.Add(label1);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxWaiterFullName);
Margin = new Padding(3, 4, 3, 4);
Name = "FormOrder";
Text = "Счет";
Load += FormOrder_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBoxWaiterFullName;
private Button buttonSave;
private Button buttonCancel;
private Label label1;
private Label labelDish;
private Components.VisualComponents.CustomTextBox customTextBox1;
private TextBox textBoxScan;
private Label label2;
private ControlsLibraryNet60.Selected.ControlSelectedListBoxSingle controlSelectedListBoxSingle;
}
}

160
WinForms/FormOrder.cs Normal file
View File

@ -0,0 +1,160 @@
using Components.VisualComponents;
using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using Contracts.SearchModels;
using ControlsLibraryNet60.Input;
using DocumentFormat.OpenXml.Office2010.Word.DrawingShape;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinForms
{
public partial class FormOrder : Form
{
private readonly IOrderLogic _orderLogic;
private readonly IDishLogic _dishLogic;
private int? _id;
public int Id { set { _id = value; } }
public FormOrder(IOrderLogic orderLogic, IDishLogic dishLogic)
{
InitializeComponent();
_orderLogic = orderLogic;
_dishLogic = dishLogic;
customTextBox1.DatePattern = @"^(\d{2}.\d{2}.\d{4})$";
}
/// <summary>
/// Загрузка формы
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormOrder_Load(object sender, EventArgs e)
{
var listDish = _dishLogic.ReadList(null);
if (listDish != null)
{
foreach (var type in listDish)
{
controlSelectedListBoxSingle.AddElement(type.Name);
}
}
if (!_id.HasValue)
{
return;
}
try
{
var order = _orderLogic.ReadElement(new OrderSearchModel { Id = _id.Value });
if (order == null)
{
return;
}
textBoxWaiterFullName.Text = order.WaiterFullName;
controlSelectedListBoxSingle.SelectedElement = order.Dish;
textBoxScan.Text = order.PicturePath;
customTextBox1.TextBoxValue = order.OrderDate.ToString("dd MM yyyy", CultureInfo.CreateSpecificCulture("ru-RU"));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Кнопка "Сохранить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSave_Click(object sender, EventArgs e)
{
customTextBox1.DatePattern = @"^(\d{2}.\d{2}.\d{4})$";
if (string.IsNullOrEmpty(textBoxWaiterFullName.Text))
{
MessageBox.Show("Заполните ФИО официанта!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxScan.Text))
{
MessageBox.Show("Приложите скан чека!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(controlSelectedListBoxSingle.SelectedElement))
{
MessageBox.Show("Выберите блюдо!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(customTextBox1.TextBoxValue))
{
MessageBox.Show("Введите дату заказа!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
var model = new OrderBindingModel
{
Id = _id ?? 0,
WaiterFullName = textBoxWaiterFullName.Text,
Dish = controlSelectedListBoxSingle.SelectedElement,
PicturePath = textBoxScan.Text,
OrderDate = DateTime.Parse(customTextBox1.TextBoxValue).ToUniversalTime(),
};
var operatingResult = _id.HasValue ? _orderLogic.Update(model) : _orderLogic.Create(model);
if (!operatingResult)
{
throw new Exception("Ошибка при создании сущности 'Счет'!");
}
MessageBox.Show("Создание сущности 'Счет' прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Кнопка "Отмена"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void textBoxScan_Click(object sender, EventArgs e)
{
using (var dialog = new OpenFileDialog { Filter = "jpg|*.jpg" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
textBoxScan.Text = dialog.FileName.ToString();
}
}
}
}
}

120
WinForms/FormOrder.resx Normal file
View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

63
WinForms/Program.cs Normal file
View File

@ -0,0 +1,63 @@
using BusinessLogics.BusinessLogics;
using Contracts.BusinessLogicsContracts;
using Contracts.StorageContracts;
using DatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace WinForms
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
/// <summary>
/// IoC-контейнер
/// </summary>
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();
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
/// <summary>
/// Конфигурация сервисов
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
// Логгер
services.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
// IoC-контейнер, хранилища
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IDishStorage, DishStorage>();
// IoC-контейнер, бизнес-логика
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IDishLogic, DishLogic>();
// IoC-контейнер, формы отображения
services.AddTransient<FormMain>();
services.AddTransient<FormOrder>();
services.AddTransient<FormDish>();
}
}
}

47
WinForms/WinForms.csproj Normal file
View File

@ -0,0 +1,47 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<OutputType>WinExe</OutputType>
</PropertyGroup>
<ItemGroup>
<None Remove="nlog.config" />
</ItemGroup>
<ItemGroup>
<Content Include="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="ComponentsLibraryNet60" Version="1.0.0" />
<PackageReference Include="ControlsLibraryNet60" Version="1.0.0" />
<PackageReference Include="CustomComponents" Version="1.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.13">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.14" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BusinessLogics\BusinessLogics.csproj" />
<ProjectReference Include="..\Components\Components.csproj" />
<ProjectReference Include="..\Contracts\Contracts.csproj" />
<ProjectReference Include="..\DatabaseImplement\DatabaseImplement.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="packages\" />
</ItemGroup>
</Project>

15
WinForms/nlog.config Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="log-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minLevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>