Compare commits

...

8 Commits
master ... Lab8

Author SHA1 Message Date
a22c8352bf lab8 2024-06-22 09:32:05 +04:00
722792852e lab7 2024-06-22 01:05:59 +04:00
4e86563468 lab6 2024-06-21 19:36:33 +04:00
94eb49d5de lab5 2024-06-21 16:40:28 +04:00
700e2efbde Лабораторная 4 2024-05-17 20:16:17 +04:00
529c1f19e4 Лабораторная 3 2024-05-17 20:02:35 +04:00
27f2e6a83f Лабораторная 2 2024-05-17 19:59:45 +04:00
8dfc5b2a93 Лабораторная 1 2024-05-17 19:48:49 +04:00
290 changed files with 88537 additions and 0 deletions

BIN
Bar/1.docx Normal file

Binary file not shown.

BIN
Bar/1.pdf Normal file

Binary file not shown.

BIN
Bar/1.xlsx Normal file

Binary file not shown.

73
Bar/Bar.sln Normal file
View File

@ -0,0 +1,73 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.1.32210.238
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BarView", "Bar\BarView.csproj", "{C2397C01-1A84-41C9-88FC-973959990385}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BarBusinessLogic", "BarBusinessLogic\BarBusinessLogic\BarBusinessLogic.csproj", "{1BB13544-63F5-4C8A-AA50-0D9174D1D0B6}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BarContracts", "BarContracts\BarContracts\BarContracts.csproj", "{E1AD000E-CCA7-45AD-9E41-412819D18B12}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BarDataModels", "BarDataModels\BarDataModels\BarDataModels.csproj", "{901C8DB1-06F1-45E8-B47B-2C035F87FCF0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BarListImplement", "BarListImplement\BarListImplement\BarListImplement.csproj", "{FE39065B-D1CA-4CF4-9274-2160A26F8A68}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BarFileImplement", "BarFileImplement\BarFileImplement\BarFileImplement.csproj", "{7B4E6858-4E4D-4D64-B9D4-536F8EC52412}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BarDatabaseImplement", "BarDatabaseImplement\BarDatabaseImplement\BarDatabaseImplement.csproj", "{DBBB5E6B-D6D6-4910-B97F-7568D24D66B1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BarRestApi", "BarRestApi\BarRestApi.csproj", "{29D4CE2C-D5AC-4B02-ADED-5A3D50A10523}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BarClientApp", "BarClientApp\BarClientApp.csproj", "{81EA0BE6-89C9-4553-BB06-B8977A342772}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C2397C01-1A84-41C9-88FC-973959990385}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C2397C01-1A84-41C9-88FC-973959990385}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C2397C01-1A84-41C9-88FC-973959990385}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C2397C01-1A84-41C9-88FC-973959990385}.Release|Any CPU.Build.0 = Release|Any CPU
{1BB13544-63F5-4C8A-AA50-0D9174D1D0B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BB13544-63F5-4C8A-AA50-0D9174D1D0B6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BB13544-63F5-4C8A-AA50-0D9174D1D0B6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BB13544-63F5-4C8A-AA50-0D9174D1D0B6}.Release|Any CPU.Build.0 = Release|Any CPU
{E1AD000E-CCA7-45AD-9E41-412819D18B12}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E1AD000E-CCA7-45AD-9E41-412819D18B12}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E1AD000E-CCA7-45AD-9E41-412819D18B12}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E1AD000E-CCA7-45AD-9E41-412819D18B12}.Release|Any CPU.Build.0 = Release|Any CPU
{901C8DB1-06F1-45E8-B47B-2C035F87FCF0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{901C8DB1-06F1-45E8-B47B-2C035F87FCF0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{901C8DB1-06F1-45E8-B47B-2C035F87FCF0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{901C8DB1-06F1-45E8-B47B-2C035F87FCF0}.Release|Any CPU.Build.0 = Release|Any CPU
{FE39065B-D1CA-4CF4-9274-2160A26F8A68}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FE39065B-D1CA-4CF4-9274-2160A26F8A68}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FE39065B-D1CA-4CF4-9274-2160A26F8A68}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FE39065B-D1CA-4CF4-9274-2160A26F8A68}.Release|Any CPU.Build.0 = Release|Any CPU
{7B4E6858-4E4D-4D64-B9D4-536F8EC52412}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7B4E6858-4E4D-4D64-B9D4-536F8EC52412}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7B4E6858-4E4D-4D64-B9D4-536F8EC52412}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7B4E6858-4E4D-4D64-B9D4-536F8EC52412}.Release|Any CPU.Build.0 = Release|Any CPU
{DBBB5E6B-D6D6-4910-B97F-7568D24D66B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DBBB5E6B-D6D6-4910-B97F-7568D24D66B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DBBB5E6B-D6D6-4910-B97F-7568D24D66B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DBBB5E6B-D6D6-4910-B97F-7568D24D66B1}.Release|Any CPU.Build.0 = Release|Any CPU
{29D4CE2C-D5AC-4B02-ADED-5A3D50A10523}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{29D4CE2C-D5AC-4B02-ADED-5A3D50A10523}.Debug|Any CPU.Build.0 = Debug|Any CPU
{29D4CE2C-D5AC-4B02-ADED-5A3D50A10523}.Release|Any CPU.ActiveCfg = Release|Any CPU
{29D4CE2C-D5AC-4B02-ADED-5A3D50A10523}.Release|Any CPU.Build.0 = Release|Any CPU
{81EA0BE6-89C9-4553-BB06-B8977A342772}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{81EA0BE6-89C9-4553-BB06-B8977A342772}.Debug|Any CPU.Build.0 = Debug|Any CPU
{81EA0BE6-89C9-4553-BB06-B8977A342772}.Release|Any CPU.ActiveCfg = Release|Any CPU
{81EA0BE6-89C9-4553-BB06-B8977A342772}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6DB86F5F-AD60-412B-970D-005AB04C72EB}
EndGlobalSection
EndGlobal

11
Bar/Bar/App.config Normal file
View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SmtpClientHost" value="smtp.gmail.com" />
<add key="SmtpClientPort" value="587" />
<add key="PopHost" value="pop.gmail.com" />
<add key="PopPort" value="995" />
<add key="MailLogin" value="danilafilippov7299@gmail.com" />
<add key="MailPassword" value="ayks nyia mgiv hzlf" />
</appSettings>
</configuration>

35
Bar/Bar/BarView.csproj Normal file
View File

@ -0,0 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.18">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.3.2" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BarBusinessLogic\BarBusinessLogic\BarBusinessLogic.csproj" />
<ProjectReference Include="..\BarContracts\BarContracts\BarContracts.csproj" />
<ProjectReference Include="..\BarDatabaseImplement\BarDatabaseImplement\BarDatabaseImplement.csproj" />
<ProjectReference Include="..\BarFileImplement\BarFileImplement\BarFileImplement.csproj" />
<ProjectReference Include="..\BarListImplement\BarListImplement\BarListImplement.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="ReportOrder.rdlc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,44 @@
using BarContracts.Attrubites;
namespace BarView
{
public static class DataGridViewExtension
{
public static void FillAndConfigGrid<T>(this DataGridView Grid, List<T>? Data)
{
if (Data == null)
return;
Grid.DataSource = Data;
var Type = typeof(T);
var Properties = Type.GetProperties();
foreach (DataGridViewColumn Column in Grid.Columns)
{
var Property = Properties.FirstOrDefault(x => x.Name == Column.Name);
if (Property == null)
throw new InvalidOperationException($"В типе {Type.Name} не найдено свойство с именем {Column.Name}");
var Attribute = Property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault();
if (Attribute == null)
throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства {Property.Name}");
if (Attribute is ColumnAttribute СolumnAttr)
{
Column.HeaderText = СolumnAttr.Title;
Column.Visible = СolumnAttr.Visible;
if (СolumnAttr.IsUseAutoSize)
{
Column.AutoSizeMode = (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode), СolumnAttr.GridViewAutoSize.ToString());
}
else
{
Column.Width = СolumnAttr.Width;
}
}
}
}
}
}

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio .Net. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="ICocktailLogic" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>BarContracts.BusinessLogicContracts.ICocktailLogic, BarContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

255
Bar/Bar/FormMain.Designer.cs generated Normal file
View File

@ -0,0 +1,255 @@
namespace BarView
{
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()
{
this.CreateOrderButton = new System.Windows.Forms.Button();
this.TakeInWorkButton = new System.Windows.Forms.Button();
this.ReadyButton = new System.Windows.Forms.Button();
this.IssuedButton = new System.Windows.Forms.Button();
this.RefreshButton = new System.Windows.Forms.Button();
this.DataGridView = new System.Windows.Forms.DataGridView();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.ToolStripMenu = new System.Windows.Forms.ToolStripMenuItem();
this.ComponentsStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.CocktailStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ClientsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.EmployersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.отчётыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.списокКомпонентовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.компонентыПоИзделиямToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.списокЗаказовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.StartWorkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.MailToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// CreateOrderButton
//
this.CreateOrderButton.Location = new System.Drawing.Point(1073, 93);
this.CreateOrderButton.Name = "CreateOrderButton";
this.CreateOrderButton.Size = new System.Drawing.Size(194, 40);
this.CreateOrderButton.TabIndex = 9;
this.CreateOrderButton.Text = "Создать заказ";
this.CreateOrderButton.UseVisualStyleBackColor = true;
this.CreateOrderButton.Click += new System.EventHandler(this.CreateOrderButton_Click);
//
// TakeInWorkButton
//
this.TakeInWorkButton.Location = new System.Drawing.Point(1073, 148);
this.TakeInWorkButton.Name = "TakeInWorkButton";
this.TakeInWorkButton.Size = new System.Drawing.Size(194, 40);
this.TakeInWorkButton.TabIndex = 10;
this.TakeInWorkButton.Text = "Отдать на выполнение";
this.TakeInWorkButton.UseVisualStyleBackColor = true;
this.TakeInWorkButton.Click += new System.EventHandler(this.TakeOrderInWorkButton_Click);
//
// ReadyButton
//
this.ReadyButton.Location = new System.Drawing.Point(1073, 207);
this.ReadyButton.Name = "ReadyButton";
this.ReadyButton.Size = new System.Drawing.Size(194, 40);
this.ReadyButton.TabIndex = 11;
this.ReadyButton.Text = "Заказ готов";
this.ReadyButton.UseVisualStyleBackColor = true;
this.ReadyButton.Click += new System.EventHandler(this.OrderReadyButton_Click);
//
// IssuedButton
//
this.IssuedButton.Location = new System.Drawing.Point(1073, 264);
this.IssuedButton.Name = "IssuedButton";
this.IssuedButton.Size = new System.Drawing.Size(194, 40);
this.IssuedButton.TabIndex = 12;
this.IssuedButton.Text = "Заказ выдан";
this.IssuedButton.UseVisualStyleBackColor = true;
this.IssuedButton.Click += new System.EventHandler(this.OrderDeliveredButton_Click);
//
// RefreshButton
//
this.RefreshButton.Location = new System.Drawing.Point(1073, 325);
this.RefreshButton.Name = "RefreshButton";
this.RefreshButton.Size = new System.Drawing.Size(194, 40);
this.RefreshButton.TabIndex = 13;
this.RefreshButton.Text = "Обновить список";
this.RefreshButton.UseVisualStyleBackColor = true;
this.RefreshButton.Click += new System.EventHandler(this.RefreshButton_Click);
//
// DataGridView
//
this.DataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.DataGridView.Location = new System.Drawing.Point(12, 46);
this.DataGridView.Name = "DataGridView";
this.DataGridView.RowHeadersWidth = 51;
this.DataGridView.RowTemplate.Height = 29;
this.DataGridView.Size = new System.Drawing.Size(1029, 362);
this.DataGridView.TabIndex = 14;
//
// menuStrip1
//
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ToolStripMenu,
this.отчётыToolStripMenuItem,
this.StartWorkToolStripMenuItem,
this.MailToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(1279, 28);
this.menuStrip1.TabIndex = 15;
this.menuStrip1.Text = "menuStrip1";
//
// ToolStripMenu
//
this.ToolStripMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ComponentsStripMenuItem,
this.CocktailStripMenuItem,
this.ClientsToolStripMenuItem,
this.EmployersToolStripMenuItem});
this.ToolStripMenu.Name = "ToolStripMenu";
this.ToolStripMenu.Size = new System.Drawing.Size(117, 24);
this.ToolStripMenu.Text = "Справочники";
//
// ComponentsStripMenuItem
//
this.ComponentsStripMenuItem.Name = "ComponentsStripMenuItem";
this.ComponentsStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.ComponentsStripMenuItem.Text = "Компоненты";
this.ComponentsStripMenuItem.Click += new System.EventHandler(this.ComponentsStripMenuItem_Click);
//
// CocktailStripMenuItem
//
this.CocktailStripMenuItem.Name = "CocktailStripMenuItem";
this.CocktailStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.CocktailStripMenuItem.Text = "Коктейль";
this.CocktailStripMenuItem.Click += new System.EventHandler(this.CocktailsStripMenuItem_Click);
//
// ClientsToolStripMenuItem
//
this.ClientsToolStripMenuItem.Name = "ClientsToolStripMenuItem";
this.ClientsToolStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.ClientsToolStripMenuItem.Text = "Клиенты";
this.ClientsToolStripMenuItem.Click += new System.EventHandler(this.ClientsToolStripMenuItem_Click);
//
// EmployersToolStripMenuItem
//
this.EmployersToolStripMenuItem.Name = "EmployersToolStripMenuItem";
this.EmployersToolStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.EmployersToolStripMenuItem.Text = "Исполнители";
this.EmployersToolStripMenuItem.Click += new System.EventHandler(this.EmployersToolStripMenuItem_Click);
//
// отчётыToolStripMenuItem
//
this.отчётыToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.списокКомпонентовToolStripMenuItem,
this.компонентыПоИзделиямToolStripMenuItem,
this.списокЗаказовToolStripMenuItem});
this.отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem";
this.отчётыToolStripMenuItem.Size = new System.Drawing.Size(73, 24);
this.отчётыToolStripMenuItem.Text = "Отчёты";
//
// списокКомпонентовToolStripMenuItem
//
this.списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem";
this.списокКомпонентовToolStripMenuItem.Size = new System.Drawing.Size(281, 26);
this.списокКомпонентовToolStripMenuItem.Text = "Список компонентов";
this.списокКомпонентовToolStripMenuItem.Click += new System.EventHandler(this.ComponentsToolStripMenuItem_Click);
//
// компонентыПоИзделиямToolStripMenuItem
//
this.компонентыПоИзделиямToolStripMenuItem.Name = омпонентыПоИзделиямToolStripMenuItem";
this.компонентыПоИзделиямToolStripMenuItem.Size = new System.Drawing.Size(281, 26);
this.компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по коктейлям";
this.компонентыПоИзделиямToolStripMenuItem.Click += new System.EventHandler(this.ComponentCocktailToolStripMenuItem_Click);
//
// списокЗаказовToolStripMenuItem
//
this.списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem";
this.списокЗаказовToolStripMenuItem.Size = new System.Drawing.Size(281, 26);
this.списокЗаказовToolStripMenuItem.Text = "Список заказов";
this.списокЗаказовToolStripMenuItem.Click += new System.EventHandler(this.OrdersToolStripMenuItem_Click);
//
// StartWorkToolStripMenuItem
//
this.StartWorkToolStripMenuItem.Name = "StartWorkToolStripMenuItem";
this.StartWorkToolStripMenuItem.Size = new System.Drawing.Size(114, 24);
this.StartWorkToolStripMenuItem.Text = "Запуск работ";
this.StartWorkToolStripMenuItem.Click += new System.EventHandler(this.запускРаботToolStripMenuItem_Click);
//
// MailToolStripMenuItem
//
this.MailToolStripMenuItem.Name = "MailToolStripMenuItem";
this.MailToolStripMenuItem.Size = new System.Drawing.Size(65, 24);
this.MailToolStripMenuItem.Text = "Почта";
this.MailToolStripMenuItem.Click += new System.EventHandler(this.MailToolStripMenuItem_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1279, 450);
this.Controls.Add(this.menuStrip1);
this.Controls.Add(this.DataGridView);
this.Controls.Add(this.RefreshButton);
this.Controls.Add(this.CreateOrderButton);
this.Controls.Add(this.TakeInWorkButton);
this.Controls.Add(this.ReadyButton);
this.Controls.Add(this.IssuedButton);
this.Name = "FormMain";
this.Text = "Бар";
this.Load += new System.EventHandler(this.FormMain_Load);
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).EndInit();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button CreateOrderButton;
private Button TakeInWorkButton;
private Button ReadyButton;
private Button IssuedButton;
private Button RefreshButton;
private DataGridView DataGridView;
private MenuStrip menuStrip1;
private ToolStripMenuItem ToolStripMenu;
private ToolStripMenuItem ComponentsStripMenuItem;
private ToolStripMenuItem CocktailStripMenuItem;
private ToolStripMenuItem отчётыToolStripMenuItem;
private ToolStripMenuItem списокКомпонентовToolStripMenuItem;
private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem ClientsToolStripMenuItem;
private ToolStripMenuItem StartWorkToolStripMenuItem;
private ToolStripMenuItem EmployersToolStripMenuItem;
private ToolStripMenuItem MailToolStripMenuItem;
}
}

267
Bar/Bar/FormMain.cs Normal file
View File

@ -0,0 +1,267 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.BusinessLogicsContracts;
using BarContracts.DI;
using BarView.Forms;
using Microsoft.Extensions.Logging;
namespace BarView
{
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess;
private readonly IBackUpLogic _backUpLogic;
public FormMain(ILogger<FormMain> Logger, IOrderLogic OrderLogic, IReportLogic ReportLogic, IWorkProcess WorkProcess, IBackUpLogic backUpLogic)
{
InitializeComponent();
_logger = Logger;
_orderLogic = OrderLogic;
_reportLogic = ReportLogic;
_workProcess = WorkProcess;
_backUpLogic = backUpLogic;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
DataGridView.FillAndConfigGrid(_orderLogic.ReadList(null));
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ComponentsStripMenuItem_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormComponents>();
if (Service is FormComponents Form)
{
Form.ShowDialog();
}
}
private void CocktailsStripMenuItem_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormCocktails>();
if (Service is FormCocktails Form)
{
Form.ShowDialog();
}
}
private void CreateOrderButton_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormCreateOrder>();
if (Service is FormCreateOrder Form)
{
Form.ShowDialog();
LoadData();
}
}
private void TakeOrderInWorkButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var OperationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id });
if (!OperationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void OrderReadyButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
try
{
var OperationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id });
if (!OperationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void OrderDeliveredButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var OperationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id });
if (!OperationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e)
{
using var Dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (Dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveComponentsToWordFile(new ReportBindingModel { FileName = Dialog.FileName });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void ComponentCocktailToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormReportCocktailComponents>();
if (Service is FormReportCocktailComponents Form)
{
Form.ShowDialog();
}
}
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormReportOrders>();
if (Service is FormReportOrders Form)
{
Form.ShowDialog();
}
}
private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormClients>();
if (Service is FormClients Form)
{
Form.ShowDialog();
}
}
private void EmployersToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormImplementers>();
if (Service is FormImplementers Form)
{
Form.ShowDialog();
}
}
private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e)
{
var ImplementerLogic = DependencyManager.Instance.Resolve<IImplementerLogic>();
_workProcess.DoWork(ImplementerLogic, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void MailToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormMail>();
if (Service is FormMail Form)
{
Form.ShowDialog();
}
}
private void CreateBackupToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
if (_backUpLogic != null)
{
var FolderBrowser = new FolderBrowserDialog();
if (FolderBrowser.ShowDialog() == DialogResult.OK)
{
_backUpLogic.CreateBackUp(new BackUpSaveBindingModel
{
FolderName = FolderBrowser.SelectedPath
});
MessageBox.Show("Бекап создан", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка создания бэкапа", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CreateBackupToolStripMenuItem_Click_1(object sender, EventArgs e)
{
}
}
}

63
Bar/Bar/FormMain.resx Normal file
View File

@ -0,0 +1,63 @@
<root>
<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="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>18, 23</value>
</metadata>
</root>

74
Bar/Bar/Forms/FormClients.Designer.cs generated Normal file
View File

@ -0,0 +1,74 @@
namespace BarView.Forms
{
partial class FormClients
{
/// <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();
ButtonDelete = new Button();
((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit();
SuspendLayout();
//
// DataGridView
//
DataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
DataGridView.Location = new Point(12, 34);
DataGridView.Name = "DataGridView";
DataGridView.RowTemplate.Height = 25;
DataGridView.Size = new Size(776, 404);
DataGridView.TabIndex = 0;
//
// ButtonDelete
//
ButtonDelete.Location = new Point(12, 5);
ButtonDelete.Name = "ButtonDelete";
ButtonDelete.Size = new Size(123, 23);
ButtonDelete.TabIndex = 1;
ButtonDelete.Text = "Удалить";
ButtonDelete.UseVisualStyleBackColor = true;
ButtonDelete.Click += ButtonDelete_Click;
//
// ClientsForm
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(ButtonDelete);
Controls.Add(DataGridView);
Name = "ClientsForm";
Text = "Клиенты";
Load += FormClients_Load;
((System.ComponentModel.ISupportInitialize)DataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView DataGridView;
private Button ButtonDelete;
}
}

View File

@ -0,0 +1,79 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
namespace BarView.Forms
{
public partial class FormClients : Form
{
private readonly ILogger _logger;
private readonly IClientLogic _clientLogic;
public FormClients(ILogger<FormClients> Logger, IClientLogic ClientLogic)
{
InitializeComponent();
_logger = Logger;
_clientLogic = ClientLogic;
}
private void LoadData()
{
try
{
var List = _clientLogic.ReadList(null);
if (List != null)
{
DataGridView.DataSource = List;
DataGridView.Columns["Id"].Visible = false;
DataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
DataGridView.Columns["Email"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
DataGridView.Columns["Password"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка клиентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки клиентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FormClients_Load(object sender, EventArgs e)
{
LoadData();
}
private void ButtonDelete_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление клиента");
try
{
if (!_clientLogic.Delete(new ClientBindingModel
{
Id = Id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
}

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>

234
Bar/Bar/Forms/FormCocktail.Designer.cs generated Normal file
View File

@ -0,0 +1,234 @@
namespace BarView.Forms
{
partial class FormCocktail
{
/// <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()
{
this.NameLabel = new System.Windows.Forms.Label();
this.NameTextBox = new System.Windows.Forms.TextBox();
this.RefreshButton = new System.Windows.Forms.Button();
this.DeleteButton = new System.Windows.Forms.Button();
this.ChangeButton = new System.Windows.Forms.Button();
this.AddButton = new System.Windows.Forms.Button();
this.CancelButton = new System.Windows.Forms.Button();
this.SaveButton = new System.Windows.Forms.Button();
this.PriceTextBox = new System.Windows.Forms.TextBox();
this.PriceLabel = new System.Windows.Forms.Label();
this.DataGridView = new System.Windows.Forms.DataGridView();
this.IdColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ComponentNameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.CountColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ComponentsGroupBox = new System.Windows.Forms.GroupBox();
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit();
this.ComponentsGroupBox.SuspendLayout();
this.SuspendLayout();
//
// NameLabel
//
this.NameLabel.AutoSize = true;
this.NameLabel.Location = new System.Drawing.Point(12, 26);
this.NameLabel.Name = "NameLabel";
this.NameLabel.Size = new System.Drawing.Size(77, 20);
this.NameLabel.TabIndex = 0;
this.NameLabel.Text = "Название";
//
// NameTextBox
//
this.NameTextBox.Location = new System.Drawing.Point(101, 19);
this.NameTextBox.Name = "NameTextBox";
this.NameTextBox.Size = new System.Drawing.Size(275, 27);
this.NameTextBox.TabIndex = 1;
//
// RefreshButton
//
this.RefreshButton.Location = new System.Drawing.Point(448, 215);
this.RefreshButton.Name = "RefreshButton";
this.RefreshButton.Size = new System.Drawing.Size(94, 29);
this.RefreshButton.TabIndex = 8;
this.RefreshButton.Text = "Обновить";
this.RefreshButton.UseVisualStyleBackColor = true;
this.RefreshButton.Click += new System.EventHandler(this.RefreshButton_Click);
//
// DeleteButton
//
this.DeleteButton.Location = new System.Drawing.Point(448, 158);
this.DeleteButton.Name = "DeleteButton";
this.DeleteButton.Size = new System.Drawing.Size(94, 29);
this.DeleteButton.TabIndex = 7;
this.DeleteButton.Text = "Удалить";
this.DeleteButton.UseVisualStyleBackColor = true;
this.DeleteButton.Click += new System.EventHandler(this.DeleteButton_Click);
//
// ChangeButton
//
this.ChangeButton.Location = new System.Drawing.Point(448, 99);
this.ChangeButton.Name = "ChangeButton";
this.ChangeButton.Size = new System.Drawing.Size(94, 29);
this.ChangeButton.TabIndex = 6;
this.ChangeButton.Text = "Изменить";
this.ChangeButton.UseVisualStyleBackColor = true;
this.ChangeButton.Click += new System.EventHandler(this.UpdateButton_Click);
//
// AddButton
//
this.AddButton.Location = new System.Drawing.Point(448, 44);
this.AddButton.Name = "AddButton";
this.AddButton.Size = new System.Drawing.Size(94, 29);
this.AddButton.TabIndex = 5;
this.AddButton.Text = "Добавить";
this.AddButton.UseVisualStyleBackColor = true;
this.AddButton.Click += new System.EventHandler(this.AddButton_Click);
//
// CancelButton
//
this.CancelButton.Location = new System.Drawing.Point(309, 400);
this.CancelButton.Name = "CancelButton";
this.CancelButton.Size = new System.Drawing.Size(94, 29);
this.CancelButton.TabIndex = 10;
this.CancelButton.Text = "Отмена";
this.CancelButton.UseVisualStyleBackColor = true;
this.CancelButton.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// SaveButton
//
this.SaveButton.Location = new System.Drawing.Point(209, 400);
this.SaveButton.Name = "SaveButton";
this.SaveButton.Size = new System.Drawing.Size(94, 29);
this.SaveButton.TabIndex = 9;
this.SaveButton.Text = "Сохранить";
this.SaveButton.UseVisualStyleBackColor = true;
this.SaveButton.Click += new System.EventHandler(this.SaveButton_Click);
//
// PriceTextBox
//
this.PriceTextBox.Location = new System.Drawing.Point(101, 70);
this.PriceTextBox.Name = "PriceTextBox";
this.PriceTextBox.ReadOnly = true;
this.PriceTextBox.Size = new System.Drawing.Size(275, 27);
this.PriceTextBox.TabIndex = 11;
//
// PriceLabel
//
this.PriceLabel.AutoSize = true;
this.PriceLabel.Location = new System.Drawing.Point(12, 77);
this.PriceLabel.Name = "PriceLabel";
this.PriceLabel.Size = new System.Drawing.Size(83, 20);
this.PriceLabel.TabIndex = 12;
this.PriceLabel.Text = "Стоимость";
//
// DataGridView
//
this.DataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.DataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.IdColumn,
this.ComponentNameColumn,
this.CountColumn});
this.DataGridView.Location = new System.Drawing.Point(19, 44);
this.DataGridView.Name = "DataGridView";
this.DataGridView.RowHeadersWidth = 51;
this.DataGridView.RowTemplate.Height = 29;
this.DataGridView.Size = new System.Drawing.Size(391, 213);
this.DataGridView.TabIndex = 13;
//this.DataGridView.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DataGridView_CellContentClick);
//
// IdColumn
//
this.IdColumn.HeaderText = "Id";
this.IdColumn.MinimumWidth = 6;
this.IdColumn.Name = "IdColumn";
this.IdColumn.Visible = false;
this.IdColumn.Width = 125;
//
// ComponentNameColumn
//
this.ComponentNameColumn.HeaderText = "Название";
this.ComponentNameColumn.MinimumWidth = 6;
this.ComponentNameColumn.Name = "ComponentNameColumn";
this.ComponentNameColumn.Width = 125;
//
// CountColumn
//
this.CountColumn.HeaderText = "Количество";
this.CountColumn.MinimumWidth = 6;
this.CountColumn.Name = "CountColumn";
this.CountColumn.Width = 125;
//
// ComponentsGroupBox
//
this.ComponentsGroupBox.Controls.Add(this.DataGridView);
this.ComponentsGroupBox.Controls.Add(this.AddButton);
this.ComponentsGroupBox.Controls.Add(this.ChangeButton);
this.ComponentsGroupBox.Controls.Add(this.DeleteButton);
this.ComponentsGroupBox.Controls.Add(this.RefreshButton);
this.ComponentsGroupBox.Location = new System.Drawing.Point(12, 118);
this.ComponentsGroupBox.Name = "ComponentsGroupBox";
this.ComponentsGroupBox.Size = new System.Drawing.Size(574, 276);
this.ComponentsGroupBox.TabIndex = 14;
this.ComponentsGroupBox.TabStop = false;
this.ComponentsGroupBox.Text = "Компоненты";
//
// FormCocktail
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.ComponentsGroupBox);
this.Controls.Add(this.PriceLabel);
this.Controls.Add(this.PriceTextBox);
this.Controls.Add(this.CancelButton);
this.Controls.Add(this.SaveButton);
this.Controls.Add(this.NameTextBox);
this.Controls.Add(this.NameLabel);
this.Name = "FormCocktail";
this.Text = "Коктейль";
this.Load += new System.EventHandler(this.FormCocktail_Load);
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).EndInit();
this.ComponentsGroupBox.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label NameLabel;
private TextBox NameTextBox;
private Button RefreshButton;
private Button DeleteButton;
private Button ChangeButton;
private Button AddButton;
private Button CancelButton;
private Button SaveButton;
private TextBox PriceTextBox;
private Label PriceLabel;
private DataGridView DataGridView;
private GroupBox ComponentsGroupBox;
private DataGridViewTextBoxColumn IdColumn;
private DataGridViewTextBoxColumn ComponentNameColumn;
private DataGridViewTextBoxColumn CountColumn;
}
}

View File

@ -0,0 +1,237 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.DI;
using BarContracts.SearchModels;
using BarDataModels.Models;
using Microsoft.Extensions.Logging;
namespace BarView.Forms
{
public partial class FormCocktail : Form
{
private readonly ILogger _logger;
private readonly ICocktailLogic _logic;
private int? _id;
private Dictionary<int, (IComponentModel, int)> _cocktailComponents;
public int Id { set { _id = value; } }
public FormCocktail(ILogger<FormCocktail> Logger, ICocktailLogic Logic)
{
InitializeComponent();
_logger = Logger;
_logic = Logic;
_cocktailComponents = new Dictionary<int, (IComponentModel, int)>();
}
private void FormCocktail_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка коктейльа");
try
{
var View = _logic.ReadElement(new CocktailSearchModel
{
Id = _id.Value
});
if (View != null)
{
NameTextBox.Text = View.CocktailName;
PriceTextBox.Text = View.Price.ToString();
_cocktailComponents = View.CocktailComponents ?? new Dictionary<int, (IComponentModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки коктейльа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка компонентов коктейльа");
try
{
if (_cocktailComponents != null)
{
DataGridView.Rows.Clear();
foreach (var Comp in _cocktailComponents)
{
DataGridView.Rows.Add(new object[] { Comp.Key, Comp.Value.Item1.ComponentName, Comp.Value.Item2 });
}
PriceTextBox.Text = CalcPrice().ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонентов коктейльа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AddButton_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormCocktailComponent>();
if (Service is FormCocktailComponent Form)
{
if (Form.ShowDialog() == DialogResult.OK)
{
if (Form.ComponentModel == null)
{
return;
}
_logger.LogInformation("Добавление нового компонента: {ComponentName} - {Count}", Form.ComponentModel.ComponentName, Form.Count);
if (_cocktailComponents.ContainsKey(Form.Id))
{
_cocktailComponents[Form.Id] = (Form.ComponentModel, Form.Count);
}
else
{
_cocktailComponents.Add(Form.Id, (Form.ComponentModel, Form.Count));
}
LoadData();
}
}
}
private void UpdateButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
var service = DependencyManager.Instance.Resolve<FormCocktailComponent>();
if (service is FormCocktailComponent Form)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells[0].Value);
Form.Id = id;
Form.Count = _cocktailComponents[id].Item2;
if (Form.ShowDialog() == DialogResult.OK)
{
if (Form.ComponentModel == null)
{
return;
}
_logger.LogInformation("Изменение компонента: {ComponentName} - {Count}", Form.ComponentModel.ComponentName, Form.Count);
_cocktailComponents[Form.Id] = (Form.ComponentModel, Form.Count);
LoadData();
}
}
}
}
private void DeleteButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
_logger.LogInformation("Удаление компонента: {ComponentName} - {Count}", DataGridView.SelectedRows[0].Cells[1].Value,
DataGridView.SelectedRows[0].Cells[2].Value);
_cocktailComponents?.Remove(Convert.ToInt32(DataGridView.SelectedRows[0].Cells[0].Value));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
private void SaveButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(NameTextBox.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(PriceTextBox.Text))
{
MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (_cocktailComponents == null || _cocktailComponents.Count == 0)
{
MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение коктейльа");
try
{
var Мodel = new CocktailBindingModel
{
Id = _id ?? 0,
CocktailName = NameTextBox.Text,
Price = Convert.ToDouble(PriceTextBox.Text),
CocktailComponents = _cocktailComponents
};
var OperationResult = _id.HasValue ? _logic.Update(Мodel) : _logic.Create(Мodel);
if (!OperationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения коктейльа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private double CalcPrice()
{
double Price = 0;
foreach (var Elem in _cocktailComponents)
{
Price += ((Elem.Value.Item1?.Cost ?? 0) * Elem.Value.Item2);
}
return Math.Round(Price * 1.1, 2);
}
}
}

View File

@ -0,0 +1,69 @@
<root>
<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="IdColumn.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ComponentNameColumn.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="CountColumn.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,119 @@
namespace BarView.Forms
{
partial class FormCocktailComponent
{
/// <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()
{
this.ComboBox = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.CountTextBox = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// ComboBox
//
this.ComboBox.FormattingEnabled = true;
this.ComboBox.Location = new System.Drawing.Point(110, 26);
this.ComboBox.Name = "ComboBox";
this.ComboBox.Size = new System.Drawing.Size(227, 28);
this.ComboBox.TabIndex = 0;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(10, 29);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(88, 20);
this.label1.TabIndex = 1;
this.label1.Text = "Компонент";
//
// CountTextBox
//
this.CountTextBox.Location = new System.Drawing.Point(110, 72);
this.CountTextBox.Name = "CountTextBox";
this.CountTextBox.Size = new System.Drawing.Size(227, 27);
this.CountTextBox.TabIndex = 2;
//
// button1
//
this.button1.Location = new System.Drawing.Point(91, 130);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(94, 29);
this.button1.TabIndex = 3;
this.button1.Text = "Сохранить";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.ButtonSave_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(191, 130);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(94, 29);
this.button2.TabIndex = 4;
this.button2.Text = "Отмена";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(10, 75);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(90, 20);
this.label2.TabIndex = 5;
this.label2.Text = "Количество";
//
// FormCocktailComponent
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(388, 219);
this.Controls.Add(this.label2);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.CountTextBox);
this.Controls.Add(this.label1);
this.Controls.Add(this.ComboBox);
this.Name = "FormCocktailComponent";
this.Text = "Компонент коктейля";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ComboBox ComboBox;
private Label label1;
private TextBox CountTextBox;
private Button button1;
private Button button2;
private Label label2;
}
}

View File

@ -0,0 +1,89 @@
using BarContracts.BusinessLogicContracts;
using BarContracts.ViewModels;
using BarDataModels.Models;
namespace BarView.Forms
{
public partial class FormCocktailComponent : Form
{
private readonly List<ComponentViewModel>? _list;
public int Id
{
get
{
return Convert.ToInt32(ComboBox.SelectedValue);
}
set
{
ComboBox.SelectedValue = value;
}
}
public IComponentModel? ComponentModel
{
get
{
if (_list == null)
{
return null;
}
foreach (var Elem in _list)
{
if (Elem.Id == Id)
{
return Elem;
}
}
return null;
}
}
public int Count
{
get { return Convert.ToInt32(CountTextBox.Text); }
set { CountTextBox.Text = value.ToString(); }
}
public FormCocktailComponent(IComponentLogic Logic)
{
InitializeComponent();
_list = Logic.ReadList(null);
if (_list != null)
{
ComboBox.DisplayMember = "ComponentName";
ComboBox.ValueMember = "Id";
ComboBox.DataSource = _list;
ComboBox.SelectedItem = null;
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(CountTextBox.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (ComboBox.SelectedValue == null)
{
MessageBox.Show("Выберите компонент", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DialogResult = DialogResult.OK;
Close();
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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>

116
Bar/Bar/Forms/FormCocktails.Designer.cs generated Normal file
View File

@ -0,0 +1,116 @@
namespace BarView.Forms
{
partial class FormCocktails
{
/// <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()
{
this.RefreshButton = new System.Windows.Forms.Button();
this.DeleteButton = new System.Windows.Forms.Button();
this.ChangeButton = new System.Windows.Forms.Button();
this.AddButton = new System.Windows.Forms.Button();
this.DataGridView = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit();
this.SuspendLayout();
//
// RefreshButton
//
this.RefreshButton.Location = new System.Drawing.Point(571, 196);
this.RefreshButton.Name = "RefreshButton";
this.RefreshButton.Size = new System.Drawing.Size(94, 29);
this.RefreshButton.TabIndex = 9;
this.RefreshButton.Text = "Обновить";
this.RefreshButton.UseVisualStyleBackColor = true;
this.RefreshButton.Click += new System.EventHandler(this.RefreshButton_Click);
//
// DeleteButton
//
this.DeleteButton.Location = new System.Drawing.Point(571, 139);
this.DeleteButton.Name = "DeleteButton";
this.DeleteButton.Size = new System.Drawing.Size(94, 29);
this.DeleteButton.TabIndex = 8;
this.DeleteButton.Text = "Удалить";
this.DeleteButton.UseVisualStyleBackColor = true;
this.DeleteButton.Click += new System.EventHandler(this.DeleteButton_Click);
//
// ChangeButton
//
this.ChangeButton.Location = new System.Drawing.Point(571, 80);
this.ChangeButton.Name = "ChangeButton";
this.ChangeButton.Size = new System.Drawing.Size(94, 29);
this.ChangeButton.TabIndex = 7;
this.ChangeButton.Text = "Изменить";
this.ChangeButton.UseVisualStyleBackColor = true;
this.ChangeButton.Click += new System.EventHandler(this.UpdateButton_Click);
//
// AddButton
//
this.AddButton.Location = new System.Drawing.Point(571, 25);
this.AddButton.Name = "AddButton";
this.AddButton.Size = new System.Drawing.Size(94, 29);
this.AddButton.TabIndex = 6;
this.AddButton.Text = "Добавить";
this.AddButton.UseVisualStyleBackColor = true;
this.AddButton.Click += new System.EventHandler(this.AddButton_Click);
//
// DataGridView
//
this.DataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.DataGridView.Location = new System.Drawing.Point(12, 25);
this.DataGridView.Name = "DataGridView";
this.DataGridView.RowHeadersWidth = 51;
this.DataGridView.RowTemplate.Height = 29;
this.DataGridView.Size = new System.Drawing.Size(542, 385);
this.DataGridView.TabIndex = 5;
//this.DataGridView.SelectionChanged += new System.EventHandler(this.DataGridView_SelectionChanged);
//
// FormCocktails
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(683, 439);
this.Controls.Add(this.RefreshButton);
this.Controls.Add(this.DeleteButton);
this.Controls.Add(this.ChangeButton);
this.Controls.Add(this.AddButton);
this.Controls.Add(this.DataGridView);
this.Name = "FormCocktails";
this.Text = "Коктейли";
this.Load += new System.EventHandler(this.FormCocktails_Load);
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Button RefreshButton;
private Button DeleteButton;
private Button ChangeButton;
private Button AddButton;
private DataGridView DataGridView;
}
}

View File

@ -0,0 +1,106 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.DI;
using Microsoft.Extensions.Logging;
namespace BarView.Forms
{
public partial class FormCocktails : Form
{
private readonly ILogger _logger;
private readonly ICocktailLogic _logic;
public FormCocktails(ILogger<FormCocktails> Logger, ICocktailLogic Logic)
{
InitializeComponent();
_logger = Logger;
_logic = Logic;
}
private void FormCocktails_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
DataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка коктейльа");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки коктейльа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AddButton_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormCocktail>();
if (Service is FormCocktail Form)
{
if (Form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void UpdateButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
var Service = DependencyManager.Instance.Resolve<FormCocktail>();
if (Service is FormCocktail Form)
{
var Temp = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
Form.Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
if (Form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void DeleteButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление коктейльа");
try
{
if (!_logic.Delete(new CocktailBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления коктейльа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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>

119
Bar/Bar/Forms/FormComponent.Designer.cs generated Normal file
View File

@ -0,0 +1,119 @@
namespace BarView.Forms
{
partial class FormComponent
{
/// <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()
{
this.Save = new System.Windows.Forms.Button();
this.ComponentNameTextBox = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.ComponentPriceTextBox = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// Save
//
this.Save.Location = new System.Drawing.Point(68, 132);
this.Save.Name = "Save";
this.Save.Size = new System.Drawing.Size(94, 29);
this.Save.TabIndex = 0;
this.Save.Text = "Сохранить";
this.Save.UseVisualStyleBackColor = true;
this.Save.Click += new System.EventHandler(this.ButtonSave_Click);
//
// ComponentNameTextBox
//
this.ComponentNameTextBox.Location = new System.Drawing.Point(99, 23);
this.ComponentNameTextBox.Name = "ComponentNameTextBox";
this.ComponentNameTextBox.Size = new System.Drawing.Size(234, 27);
this.ComponentNameTextBox.TabIndex = 1;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 26);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 20);
this.label1.TabIndex = 2;
this.label1.Text = "Название:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 69);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(48, 20);
this.label2.TabIndex = 3;
this.label2.Text = "Цена:";
//
// ComponentPriceTextBox
//
this.ComponentPriceTextBox.Location = new System.Drawing.Point(99, 62);
this.ComponentPriceTextBox.Name = "ComponentPriceTextBox";
this.ComponentPriceTextBox.Size = new System.Drawing.Size(234, 27);
this.ComponentPriceTextBox.TabIndex = 4;
//
// button1
//
this.button1.Location = new System.Drawing.Point(168, 132);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(94, 29);
this.button1.TabIndex = 5;
this.button1.Text = "Отмена";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// FormComponent
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(345, 183);
this.Controls.Add(this.button1);
this.Controls.Add(this.ComponentPriceTextBox);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.ComponentNameTextBox);
this.Controls.Add(this.Save);
this.Name = "FormComponent";
this.Text = "Компонент";
this.Load += new System.EventHandler(this.FormComponent_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button Save;
private TextBox ComponentNameTextBox;
private Label label1;
private Label label2;
private TextBox ComponentPriceTextBox;
private Button button1;
}
}

View File

@ -0,0 +1,95 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace BarView.Forms
{
public partial class FormComponent : Form
{
private readonly ILogger _logger;
private readonly IComponentLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormComponent(ILogger<FormComponent> Logger, IComponentLogic Logic)
{
InitializeComponent();
_logger = Logger;
_logic = Logic;
}
private void FormComponent_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение компонента");
var View = _logic.ReadElement(new ComponentSearchModel
{
Id = _id.Value
});
if (View != null)
{
ComponentNameTextBox.Text = View.ComponentName;
ComponentPriceTextBox.Text = View.Cost.ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(ComponentNameTextBox.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение компонента");
try
{
var model = new ComponentBindingModel
{
Id = _id ?? 0,
ComponentName = ComponentNameTextBox.Text,
Cost = Convert.ToDouble(ComponentPriceTextBox.Text)
};
var OperationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!OperationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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>

115
Bar/Bar/Forms/FormComponents.Designer.cs generated Normal file
View File

@ -0,0 +1,115 @@
namespace BarView.Forms
{
partial class FormComponents
{
/// <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()
{
this.DataGridView = new System.Windows.Forms.DataGridView();
this.AddButton = new System.Windows.Forms.Button();
this.ChangeButton = new System.Windows.Forms.Button();
this.DeleteButton = new System.Windows.Forms.Button();
this.RefreshButton = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit();
this.SuspendLayout();
//
// DataGridView
//
this.DataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.DataGridView.Location = new System.Drawing.Point(12, 30);
this.DataGridView.Name = "DataGridView";
this.DataGridView.RowHeadersWidth = 51;
this.DataGridView.RowTemplate.Height = 29;
this.DataGridView.Size = new System.Drawing.Size(542, 385);
this.DataGridView.TabIndex = 0;
//
// AddButton
//
this.AddButton.Location = new System.Drawing.Point(571, 30);
this.AddButton.Name = "AddButton";
this.AddButton.Size = new System.Drawing.Size(94, 29);
this.AddButton.TabIndex = 1;
this.AddButton.Text = "Добавить";
this.AddButton.UseVisualStyleBackColor = true;
this.AddButton.Click += new System.EventHandler(this.AddButton_Click);
//
// ChangeButton
//
this.ChangeButton.Location = new System.Drawing.Point(571, 85);
this.ChangeButton.Name = "ChangeButton";
this.ChangeButton.Size = new System.Drawing.Size(94, 29);
this.ChangeButton.TabIndex = 2;
this.ChangeButton.Text = "Изменить";
this.ChangeButton.UseVisualStyleBackColor = true;
this.ChangeButton.Click += new System.EventHandler(this.ChangeButton_Click);
//
// DeleteButton
//
this.DeleteButton.Location = new System.Drawing.Point(571, 144);
this.DeleteButton.Name = "DeleteButton";
this.DeleteButton.Size = new System.Drawing.Size(94, 29);
this.DeleteButton.TabIndex = 3;
this.DeleteButton.Text = "Удалить";
this.DeleteButton.UseVisualStyleBackColor = true;
this.DeleteButton.Click += new System.EventHandler(this.DeleteButton_Click);
//
// RefreshButton
//
this.RefreshButton.Location = new System.Drawing.Point(571, 201);
this.RefreshButton.Name = "RefreshButton";
this.RefreshButton.Size = new System.Drawing.Size(94, 29);
this.RefreshButton.TabIndex = 4;
this.RefreshButton.Text = "Обновить";
this.RefreshButton.UseVisualStyleBackColor = true;
this.RefreshButton.Click += new System.EventHandler(this.RefreshButton_Click);
//
// FormComponents
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(689, 435);
this.Controls.Add(this.RefreshButton);
this.Controls.Add(this.DeleteButton);
this.Controls.Add(this.ChangeButton);
this.Controls.Add(this.AddButton);
this.Controls.Add(this.DataGridView);
this.Name = "FormComponents";
this.Text = "Компоненты";
this.Load += new System.EventHandler(this.ComponentsForm_Load);
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView DataGridView;
private Button AddButton;
private Button ChangeButton;
private Button DeleteButton;
private Button RefreshButton;
}
}

View File

@ -0,0 +1,105 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.DI;
using Microsoft.Extensions.Logging;
namespace BarView.Forms
{
public partial class FormComponents : Form
{
private readonly ILogger _logger;
private readonly IComponentLogic _logic;
public FormComponents(ILogger<FormComponents> Logger, IComponentLogic Logic)
{
InitializeComponent();
_logger = Logger;
_logic = Logic;
}
private void ComponentsForm_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
DataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка компонентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AddButton_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormComponent>();
if (Service is FormComponent Form)
{
if (Form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ChangeButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
var Service = DependencyManager.Instance.Resolve<FormComponent>();
if (Service is FormComponent Form)
{
Form.Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
if (Form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void DeleteButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление компонента");
try
{
if (!_logic.Delete(new ComponentBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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>

168
Bar/Bar/Forms/FormCreateOrder.Designer.cs generated Normal file
View File

@ -0,0 +1,168 @@
namespace BarView.Forms
{
partial class FormCreateOrder
{
/// <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()
{
this.CancelButton = new System.Windows.Forms.Button();
this.CountTextBox = new System.Windows.Forms.TextBox();
this.CountLabel = new System.Windows.Forms.Label();
this.CocktailLabel = new System.Windows.Forms.Label();
this.SaveButton = new System.Windows.Forms.Button();
this.SumTextBox = new System.Windows.Forms.TextBox();
this.SumLabel = new System.Windows.Forms.Label();
this.CocktailComboBox = new System.Windows.Forms.ComboBox();
this.ClientComboBox = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// CancelButton
//
this.CancelButton.Location = new System.Drawing.Point(167, 184);
this.CancelButton.Name = "CancelButton";
this.CancelButton.Size = new System.Drawing.Size(94, 29);
this.CancelButton.TabIndex = 11;
this.CancelButton.Text = "Отмена";
this.CancelButton.UseVisualStyleBackColor = true;
this.CancelButton.Click += new System.EventHandler(this.CancelButton_Click);
//
// CountTextBox
//
this.CountTextBox.Location = new System.Drawing.Point(116, 56);
this.CountTextBox.Name = "CountTextBox";
this.CountTextBox.Size = new System.Drawing.Size(234, 27);
this.CountTextBox.TabIndex = 10;
this.CountTextBox.TextChanged += new System.EventHandler(this.CountTextBox_TextChanged);
//
// CountLabel
//
this.CountLabel.AutoSize = true;
this.CountLabel.Location = new System.Drawing.Point(12, 63);
this.CountLabel.Name = "CountLabel";
this.CountLabel.Size = new System.Drawing.Size(93, 20);
this.CountLabel.TabIndex = 9;
this.CountLabel.Text = "Количество:";
//
// CocktailLabel
//
this.CocktailLabel.AutoSize = true;
this.CocktailLabel.Location = new System.Drawing.Point(12, 20);
this.CocktailLabel.Name = "CocktailLabel";
this.CocktailLabel.Size = new System.Drawing.Size(76, 20);
this.CocktailLabel.TabIndex = 8;
this.CocktailLabel.Text = "Коктейль:";
//
// SaveButton
//
this.SaveButton.Location = new System.Drawing.Point(67, 184);
this.SaveButton.Name = "SaveButton";
this.SaveButton.Size = new System.Drawing.Size(94, 29);
this.SaveButton.TabIndex = 6;
this.SaveButton.Text = "Сохранить";
this.SaveButton.UseVisualStyleBackColor = true;
this.SaveButton.Click += new System.EventHandler(this.SaveButton_Click);
//
// SumTextBox
//
this.SumTextBox.Location = new System.Drawing.Point(116, 93);
this.SumTextBox.Name = "SumTextBox";
this.SumTextBox.ReadOnly = true;
this.SumTextBox.Size = new System.Drawing.Size(234, 27);
this.SumTextBox.TabIndex = 13;
//
// SumLabel
//
this.SumLabel.AutoSize = true;
this.SumLabel.Location = new System.Drawing.Point(12, 100);
this.SumLabel.Name = "SumLabel";
this.SumLabel.Size = new System.Drawing.Size(58, 20);
this.SumLabel.TabIndex = 12;
this.SumLabel.Text = "Сумма:";
//
// CocktailComboBox
//
this.CocktailComboBox.FormattingEnabled = true;
this.CocktailComboBox.Location = new System.Drawing.Point(115, 17);
this.CocktailComboBox.Name = "CocktailComboBox";
this.CocktailComboBox.Size = new System.Drawing.Size(235, 28);
this.CocktailComboBox.TabIndex = 14;
this.CocktailComboBox.SelectedIndexChanged += new System.EventHandler(this.CocktailComboBox_SelectedIndexChanged);
//
// ClientComboBox
//
this.ClientComboBox.FormattingEnabled = true;
this.ClientComboBox.Location = new System.Drawing.Point(116, 137);
this.ClientComboBox.Name = "ClientComboBox";
this.ClientComboBox.Size = new System.Drawing.Size(235, 28);
this.ClientComboBox.TabIndex = 16;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(13, 140);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(61, 20);
this.label1.TabIndex = 15;
this.label1.Text = "Клиент:";
//
// FormCreateOrder
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(362, 225);
this.Controls.Add(this.ClientComboBox);
this.Controls.Add(this.label1);
this.Controls.Add(this.CocktailComboBox);
this.Controls.Add(this.SumTextBox);
this.Controls.Add(this.SumLabel);
this.Controls.Add(this.CancelButton);
this.Controls.Add(this.CountTextBox);
this.Controls.Add(this.CountLabel);
this.Controls.Add(this.CocktailLabel);
this.Controls.Add(this.SaveButton);
this.Name = "FormCreateOrder";
this.Text = "FormCreateOrder";
this.Load += new System.EventHandler(this.FormCreateOrder_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button CancelButton;
private TextBox CountTextBox;
private Label CountLabel;
private Label CocktailLabel;
private Button SaveButton;
private TextBox SumTextBox;
private Label SumLabel;
private ComboBox CocktailComboBox;
private ComboBox ClientComboBox;
private Label label1;
}
}

View File

@ -0,0 +1,158 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace BarView.Forms
{
public partial class FormCreateOrder : Form
{
private readonly ILogger _logger;
private readonly ICocktailLogic _cocktailLogic;
private readonly IOrderLogic _orderLogic;
private readonly IClientLogic _clientLogic;
public FormCreateOrder(ILogger<FormCreateOrder> Logger, ICocktailLogic CocktailLogic, IOrderLogic OrderLogic, IClientLogic ClientLogic)
{
InitializeComponent();
_logger = Logger;
_cocktailLogic = CocktailLogic;
_orderLogic = OrderLogic;
_clientLogic = ClientLogic;
}
private void FormCreateOrder_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка коктелей для заказа");
try
{
var List = _cocktailLogic.ReadList(null);
if (List != null)
{
CocktailComboBox.DisplayMember = "CocktailName";
CocktailComboBox.ValueMember = "Id";
CocktailComboBox.DataSource = List;
CocktailComboBox.SelectedItem = null;
}
_logger.LogInformation("Коктели загружены");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки коктелей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_logger.LogInformation("Загрузка клиентов для заказа");
try
{
var list = _clientLogic.ReadList(null);
if (list != null)
{
ClientComboBox.DisplayMember = "ClientFIO";
ClientComboBox.ValueMember = "Id";
ClientComboBox.DataSource = list;
ClientComboBox.SelectedItem = null;
}
_logger.LogInformation("Клиенты загружены");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки клиентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void CalcSum()
{
if (CocktailComboBox.SelectedValue != null && !string.IsNullOrEmpty(CountTextBox.Text))
{
try
{
int id = Convert.ToInt32(CocktailComboBox.SelectedValue);
var Cocktail = _cocktailLogic.ReadElement(new CocktailSearchModel
{
Id = id
});
int Count = Convert.ToInt32(CountTextBox.Text);
SumTextBox.Text = Math.Round(Count * (Cocktail?.Price ?? 0), 2).ToString();
_logger.LogInformation("Расчет суммы заказа");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка расчета суммы заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void CountTextBox_TextChanged(object sender, EventArgs e)
{
CalcSum();
}
private void SaveButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(CountTextBox.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (CocktailComboBox.SelectedValue == null)
{
MessageBox.Show("Выберите коктель", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (ClientComboBox.SelectedValue == null)
{
MessageBox.Show("Выберите клиента", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
try
{
var OperationResult = _orderLogic.CreateOrder(new OrderBindingModel
{
CocktailId = Convert.ToInt32(CocktailComboBox.SelectedValue),
ClientId = Convert.ToInt32(ClientComboBox.SelectedValue),
Count = Convert.ToInt32(CountTextBox.Text),
Sum = Convert.ToDouble(SumTextBox.Text)
});
if (!OperationResult)
{
throw new Exception("Ошибка при создании заказа. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void CocktailComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
CalcSum();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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>

173
Bar/Bar/Forms/FormImplementer.Designer.cs generated Normal file
View File

@ -0,0 +1,173 @@
namespace BarView.Forms
{
partial class FormImplementer
{
/// <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()
{
FioTextBox = new TextBox();
FioLabel = new Label();
PasswordTextBox = new TextBox();
PasswordLabel = new Label();
WorkExperienceLabel = new Label();
WorkExperienceNumericUpDown = new NumericUpDown();
QualificationNumericUpDown = new NumericUpDown();
QualificationLabel = new Label();
CancelButton = new Button();
SaveButton = new Button();
((System.ComponentModel.ISupportInitialize)WorkExperienceNumericUpDown).BeginInit();
((System.ComponentModel.ISupportInitialize)QualificationNumericUpDown).BeginInit();
SuspendLayout();
//
// FioTextBox
//
FioTextBox.Location = new Point(137, 9);
FioTextBox.Margin = new Padding(3, 2, 3, 2);
FioTextBox.Name = "FioTextBox";
FioTextBox.Size = new Size(335, 23);
FioTextBox.TabIndex = 3;
//
// FioLabel
//
FioLabel.AutoSize = true;
FioLabel.Location = new Point(10, 12);
FioLabel.Name = "FioLabel";
FioLabel.Size = new Size(112, 15);
FioLabel.TabIndex = 2;
FioLabel.Text = "ФИО исполнителя:";
//
// PasswordTextBox
//
PasswordTextBox.Location = new Point(137, 40);
PasswordTextBox.Margin = new Padding(3, 2, 3, 2);
PasswordTextBox.Name = "PasswordTextBox";
PasswordTextBox.Size = new Size(335, 23);
PasswordTextBox.TabIndex = 5;
//
// PasswordLabel
//
PasswordLabel.AutoSize = true;
PasswordLabel.Location = new Point(10, 43);
PasswordLabel.Name = "PasswordLabel";
PasswordLabel.Size = new Size(52, 15);
PasswordLabel.TabIndex = 4;
PasswordLabel.Text = "Пароль:";
//
// WorkExperienceLabel
//
WorkExperienceLabel.AutoSize = true;
WorkExperienceLabel.Location = new Point(10, 75);
WorkExperienceLabel.Name = "WorkExperienceLabel";
WorkExperienceLabel.Size = new Size(84, 15);
WorkExperienceLabel.TabIndex = 6;
WorkExperienceLabel.Text = "Опыт работы:";
//
// WorkExperienceNumericUpDown
//
WorkExperienceNumericUpDown.Location = new Point(137, 73);
WorkExperienceNumericUpDown.Margin = new Padding(3, 2, 3, 2);
WorkExperienceNumericUpDown.Name = "WorkExperienceNumericUpDown";
WorkExperienceNumericUpDown.Size = new Size(108, 23);
WorkExperienceNumericUpDown.TabIndex = 8;
//
// QualificationNumericUpDown
//
QualificationNumericUpDown.Location = new Point(137, 106);
QualificationNumericUpDown.Margin = new Padding(3, 2, 3, 2);
QualificationNumericUpDown.Name = "QualificationNumericUpDown";
QualificationNumericUpDown.Size = new Size(108, 23);
QualificationNumericUpDown.TabIndex = 10;
//
// QualificationLabel
//
QualificationLabel.AutoSize = true;
QualificationLabel.Location = new Point(10, 108);
QualificationLabel.Name = "QualificationLabel";
QualificationLabel.Size = new Size(91, 15);
QualificationLabel.TabIndex = 9;
QualificationLabel.Text = "Квалификация:";
//
// CancelButton
//
CancelButton.Location = new Point(353, 142);
CancelButton.Margin = new Padding(3, 2, 3, 2);
CancelButton.Name = "CancelButton";
CancelButton.Size = new Size(119, 30);
CancelButton.TabIndex = 12;
CancelButton.Text = "Отмена";
CancelButton.UseVisualStyleBackColor = true;
CancelButton.Click += CancelButton_Click;
//
// SaveButton
//
SaveButton.Location = new Point(233, 142);
SaveButton.Margin = new Padding(3, 2, 3, 2);
SaveButton.Name = "SaveButton";
SaveButton.Size = new Size(114, 30);
SaveButton.TabIndex = 11;
SaveButton.Text = "Сохранить";
SaveButton.UseVisualStyleBackColor = true;
SaveButton.Click += SaveButton_Click;
//
// FormImplementer
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(482, 183);
Controls.Add(CancelButton);
Controls.Add(SaveButton);
Controls.Add(QualificationNumericUpDown);
Controls.Add(QualificationLabel);
Controls.Add(WorkExperienceNumericUpDown);
Controls.Add(WorkExperienceLabel);
Controls.Add(PasswordTextBox);
Controls.Add(PasswordLabel);
Controls.Add(FioTextBox);
Controls.Add(FioLabel);
Margin = new Padding(3, 2, 3, 2);
Name = "FormImplementer";
Text = "Исполнитель";
Load += FormImplementer_Load;
((System.ComponentModel.ISupportInitialize)WorkExperienceNumericUpDown).EndInit();
((System.ComponentModel.ISupportInitialize)QualificationNumericUpDown).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox FioTextBox;
private Label FioLabel;
private TextBox PasswordTextBox;
private Label PasswordLabel;
private Label WorkExperienceLabel;
private NumericUpDown WorkExperienceNumericUpDown;
private NumericUpDown QualificationNumericUpDown;
private Label QualificationLabel;
private Button CancelButton;
private Button SaveButton;
}
}

View File

@ -0,0 +1,105 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicsContracts;
using BarContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace BarView.Forms
{
public partial class FormImplementer : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormImplementer(ILogger<FormImplementer> Logger, IImplementerLogic Logic)
{
InitializeComponent();
_logger = Logger;
_logic = Logic;
}
private void FormImplementer_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение исполнителя");
var View = _logic.ReadElement(new ImplementerSearchModel
{
Id = _id.Value
});
if (View != null)
{
FioTextBox.Text = View.ImplementerFIO;
PasswordTextBox.Text = View.Password;
WorkExperienceNumericUpDown.Value = View.WorkExperience;
QualificationNumericUpDown.Value = View.Qualification;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void SaveButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(FioTextBox.Text))
{
MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(PasswordTextBox.Text))
{
MessageBox.Show("Заполните пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var Model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = FioTextBox.Text,
Password = PasswordTextBox.Text,
WorkExperience = (int)WorkExperienceNumericUpDown.Value,
Qualification = (int)QualificationNumericUpDown.Value
};
var OperationResult = _id.HasValue ? _logic.Update(Model) : _logic.Create(Model);
if (!OperationResult)
{
throw new Exception("Ошибка при создании или обновлении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

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>

136
Bar/Bar/Forms/FormImplementers.Designer.cs generated Normal file
View File

@ -0,0 +1,136 @@
namespace BarView.Forms
{
partial class FormImplementers
{
/// <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()
{
ToolsPanel = new Panel();
RefreshButton = new Button();
DeleteButton = new Button();
UpdateButton = new Button();
AddButton = new Button();
DataGridView = new DataGridView();
ToolsPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit();
SuspendLayout();
//
// ToolsPanel
//
ToolsPanel.Controls.Add(RefreshButton);
ToolsPanel.Controls.Add(DeleteButton);
ToolsPanel.Controls.Add(UpdateButton);
ToolsPanel.Controls.Add(AddButton);
ToolsPanel.Location = new Point(532, 9);
ToolsPanel.Margin = new Padding(3, 2, 3, 2);
ToolsPanel.Name = "ToolsPanel";
ToolsPanel.Size = new Size(116, 320);
ToolsPanel.TabIndex = 3;
//
// RefreshButton
//
RefreshButton.Location = new Point(3, 126);
RefreshButton.Margin = new Padding(3, 2, 3, 2);
RefreshButton.Name = "RefreshButton";
RefreshButton.Size = new Size(110, 27);
RefreshButton.TabIndex = 3;
RefreshButton.Text = "Обновить";
RefreshButton.UseVisualStyleBackColor = true;
RefreshButton.Click += RefreshButton_Click;
//
// DeleteButton
//
DeleteButton.Location = new Point(3, 84);
DeleteButton.Margin = new Padding(3, 2, 3, 2);
DeleteButton.Name = "DeleteButton";
DeleteButton.Size = new Size(110, 27);
DeleteButton.TabIndex = 2;
DeleteButton.Text = "Удалить";
DeleteButton.UseVisualStyleBackColor = true;
DeleteButton.Click += DeleteButton_Click;
//
// UpdateButton
//
UpdateButton.Location = new Point(3, 42);
UpdateButton.Margin = new Padding(3, 2, 3, 2);
UpdateButton.Name = "UpdateButton";
UpdateButton.Size = new Size(110, 27);
UpdateButton.TabIndex = 1;
UpdateButton.Text = "Изменить";
UpdateButton.UseVisualStyleBackColor = true;
UpdateButton.Click += UpdateButton_Click;
//
// AddButton
//
AddButton.Location = new Point(3, 2);
AddButton.Margin = new Padding(3, 2, 3, 2);
AddButton.Name = "AddButton";
AddButton.Size = new Size(110, 27);
AddButton.TabIndex = 0;
AddButton.Text = "Добавить";
AddButton.UseVisualStyleBackColor = true;
AddButton.Click += AddButton_Click;
//
// DataGridView
//
DataGridView.AllowUserToAddRows = false;
DataGridView.AllowUserToDeleteRows = false;
DataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
DataGridView.Location = new Point(10, 9);
DataGridView.Margin = new Padding(3, 2, 3, 2);
DataGridView.Name = "DataGridView";
DataGridView.ReadOnly = true;
DataGridView.RowHeadersWidth = 51;
DataGridView.RowTemplate.Height = 29;
DataGridView.Size = new Size(516, 320);
DataGridView.TabIndex = 2;
//
// FormImplementers
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(653, 338);
Controls.Add(ToolsPanel);
Controls.Add(DataGridView);
Margin = new Padding(3, 2, 3, 2);
Name = "FormImplementers";
Text = "Исполнители";
Load += FormImplementers_Load;
ToolsPanel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)DataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Panel ToolsPanel;
private Button RefreshButton;
private Button DeleteButton;
private Button UpdateButton;
private Button AddButton;
private DataGridView DataGridView;
}
}

View File

@ -0,0 +1,104 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicsContracts;
using BarContracts.DI;
using Microsoft.Extensions.Logging;
namespace BarView.Forms
{
public partial class FormImplementers : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _implementerLogic;
public FormImplementers(ILogger<FormImplementers> Logger, IImplementerLogic ImplementerLogic)
{
InitializeComponent();
_logger = Logger;
_implementerLogic = ImplementerLogic;
}
private void LoadData()
{
try
{
DataGridView.FillAndConfigGrid(_implementerLogic.ReadList(null));
_logger.LogInformation("Загрузка исполнителей");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки исполнителей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FormImplementers_Load(object sender, EventArgs e)
{
LoadData();
}
private void AddButton_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormImplementer>();
if (Service is FormImplementer Form)
{
if (Form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void UpdateButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
var service = DependencyManager.Instance.Resolve<FormImplementer>();
if (service is FormImplementer Form)
{
Form.Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
if (Form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void DeleteButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление исполнителя");
try
{
if (!_implementerLogic.Delete(new ImplementerBindingModel
{
Id = Id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

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>

68
Bar/Bar/Forms/FormMail.Designer.cs generated Normal file
View File

@ -0,0 +1,68 @@
namespace BarView.Forms
{
partial class FormMail
{
/// <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.AllowUserToDeleteRows = false;
DataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
DataGridView.Dock = DockStyle.Fill;
DataGridView.Location = new Point(0, 0);
DataGridView.Margin = new Padding(3, 2, 3, 2);
DataGridView.Name = "DataGridView";
DataGridView.ReadOnly = true;
DataGridView.RowHeadersWidth = 51;
DataGridView.RowTemplate.Height = 29;
DataGridView.Size = new Size(1084, 456);
DataGridView.TabIndex = 0;
//
// FormMail
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1084, 456);
Controls.Add(DataGridView);
Margin = new Padding(3, 2, 3, 2);
Name = "FormMail";
Text = "Письма";
Load += FormMail_Load;
((System.ComponentModel.ISupportInitialize)DataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView DataGridView;
}
}

47
Bar/Bar/Forms/FormMail.cs Normal file
View File

@ -0,0 +1,47 @@
using BarContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
namespace BarView.Forms
{
public partial class FormMail : Form
{
private readonly ILogger _logger;
private readonly IMessageInfoLogic _messageLogic;
public FormMail(ILogger<FormMail> Logger, IMessageInfoLogic MessageLogic)
{
InitializeComponent();
_logger = Logger;
_messageLogic = MessageLogic;
}
private void LoadData()
{
try
{
var List = _messageLogic.ReadList(null);
if (List != null)
{
DataGridView.DataSource = List;
DataGridView.Columns["MessageId"].Visible = false;
DataGridView.Columns["ClientId"].Visible = false;
DataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка почтовых собщений");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки почтовых сообщений");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FormMail_Load(object sender, EventArgs e)
{
LoadData();
}
}
}

120
Bar/Bar/Forms/FormMail.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

@ -0,0 +1,107 @@
namespace BarView.Forms
{
partial class FormReportCocktailComponents
{
/// <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()
{
this.ButtonSaveToExcel = new System.Windows.Forms.Button();
this.DataGridView = new System.Windows.Forms.DataGridView();
this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit();
this.SuspendLayout();
//
// ButtonSaveToExcel
//
this.ButtonSaveToExcel.Location = new System.Drawing.Point(31, 12);
this.ButtonSaveToExcel.Name = "ButtonSaveToExcel";
this.ButtonSaveToExcel.Size = new System.Drawing.Size(162, 26);
this.ButtonSaveToExcel.TabIndex = 0;
this.ButtonSaveToExcel.Text = "Сохранить в Excel";
this.ButtonSaveToExcel.UseVisualStyleBackColor = true;
this.ButtonSaveToExcel.Click += new System.EventHandler(this.ButtonSaveToExcel_Click);
//
// DataGridView
//
this.DataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.DataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column1,
this.Column2,
this.Column3});
this.DataGridView.Location = new System.Drawing.Point(12, 56);
this.DataGridView.Name = "DataGridView";
this.DataGridView.RowHeadersWidth = 51;
this.DataGridView.RowTemplate.Height = 29;
this.DataGridView.Size = new System.Drawing.Size(581, 368);
this.DataGridView.TabIndex = 1;
//
// Column1
//
this.Column1.HeaderText = "Коктейль";
this.Column1.MinimumWidth = 6;
this.Column1.Name = "Column1";
this.Column1.Width = 125;
//
// Column2
//
this.Column2.HeaderText = "Компонент";
this.Column2.MinimumWidth = 6;
this.Column2.Name = "Column2";
this.Column2.Width = 125;
//
// Column3
//
this.Column3.HeaderText = "Количество";
this.Column3.MinimumWidth = 6;
this.Column3.Name = "Column3";
this.Column3.Width = 125;
//
// FormReportCocktailComponents
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.DataGridView);
this.Controls.Add(this.ButtonSaveToExcel);
this.Name = "FormReportCocktailComponents";
this.Text = "FormReportCoctailComponents";
this.Load += new System.EventHandler(this.FormReportCoctailComponents_Load);
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Button ButtonSaveToExcel;
private DataGridView DataGridView;
private DataGridViewTextBoxColumn Column1;
private DataGridViewTextBoxColumn Column2;
private DataGridViewTextBoxColumn Column3;
}
}

View File

@ -0,0 +1,75 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
namespace BarView.Forms
{
public partial class FormReportCocktailComponents : Form
{
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportCocktailComponents(ILogger<FormReportCocktailComponents> Logger, IReportLogic Logic)
{
InitializeComponent();
_logger = Logger;
_logic = Logic;
}
private void FormReportCoctailComponents_Load(object sender, EventArgs e)
{
try
{
var Dict = _logic.GetCocktailComponents();
if (Dict != null)
{
DataGridView.Rows.Clear();
foreach (var Elem in Dict)
{
DataGridView.Rows.Add(new object[] { Elem.CocktailName, "", "" });
foreach (var ListElem in Elem.Components)
DataGridView.Rows.Add(new object[] { "", ListElem.Item1, ListElem.Item2 });
DataGridView.Rows.Add(new object[] { "Итого", "", Elem.TotalCount });
DataGridView.Rows.Add(Array.Empty<object>());
}
}
_logger.LogInformation("Загрузка списка Коктейльов по компонентам");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка Коктейльов по компонентам");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSaveToExcel_Click(object sender, EventArgs e)
{
using var Dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" };
if (Dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveCocktailComponentToExcelFile(new ReportBindingModel
{
FileName = Dialog.FileName
});
_logger.LogInformation("Сохранение списка Коктейльов по компонентам");
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка Коктейльов по компонентам");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -0,0 +1,69 @@
<root>
<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="Column1.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Column2.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Column3.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

131
Bar/Bar/Forms/FormReportOrders.Designer.cs generated Normal file
View File

@ -0,0 +1,131 @@
namespace BarView.Forms
{
partial class FormReportOrders
{
/// <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()
{
this.Panel = new System.Windows.Forms.Panel();
this.ToPdfButton = new System.Windows.Forms.Button();
this.CreateButton = new System.Windows.Forms.Button();
this.ToDateTimePicker = new System.Windows.Forms.DateTimePicker();
this.ToLabel = new System.Windows.Forms.Label();
this.FromDateTimePicker = new System.Windows.Forms.DateTimePicker();
this.FromLabel = new System.Windows.Forms.Label();
this.Panel.SuspendLayout();
this.SuspendLayout();
//
// Panel
//
this.Panel.Controls.Add(this.ToPdfButton);
this.Panel.Controls.Add(this.CreateButton);
this.Panel.Controls.Add(this.ToDateTimePicker);
this.Panel.Controls.Add(this.ToLabel);
this.Panel.Controls.Add(this.FromDateTimePicker);
this.Panel.Controls.Add(this.FromLabel);
this.Panel.Dock = System.Windows.Forms.DockStyle.Top;
this.Panel.Location = new System.Drawing.Point(0, 0);
this.Panel.Name = "Panel";
this.Panel.Size = new System.Drawing.Size(1105, 52);
this.Panel.TabIndex = 0;
//
// ToPdfButton
//
this.ToPdfButton.Location = new System.Drawing.Point(781, 9);
this.ToPdfButton.Name = "ToPdfButton";
this.ToPdfButton.Size = new System.Drawing.Size(165, 29);
this.ToPdfButton.TabIndex = 5;
this.ToPdfButton.Text = "В PDF";
this.ToPdfButton.UseVisualStyleBackColor = true;
this.ToPdfButton.Click += new System.EventHandler(this.ButtonToPdf_Click);
//
// CreateButton
//
this.CreateButton.Location = new System.Drawing.Point(542, 11);
this.CreateButton.Name = "CreateButton";
this.CreateButton.Size = new System.Drawing.Size(165, 29);
this.CreateButton.TabIndex = 4;
this.CreateButton.Text = "Сформировать";
this.CreateButton.UseVisualStyleBackColor = true;
this.CreateButton.Click += new System.EventHandler(this.ButtonMake_Click);
//
// ToDateTimePicker
//
this.ToDateTimePicker.Location = new System.Drawing.Point(299, 9);
this.ToDateTimePicker.Name = "ToDateTimePicker";
this.ToDateTimePicker.Size = new System.Drawing.Size(199, 27);
this.ToDateTimePicker.TabIndex = 3;
//
// ToLabel
//
this.ToLabel.AutoSize = true;
this.ToLabel.Location = new System.Drawing.Point(254, 13);
this.ToLabel.Name = "ToLabel";
this.ToLabel.Size = new System.Drawing.Size(27, 20);
this.ToLabel.TabIndex = 2;
this.ToLabel.Text = "по";
//
// FromDateTimePicker
//
this.FromDateTimePicker.Location = new System.Drawing.Point(37, 9);
this.FromDateTimePicker.Name = "FromDateTimePicker";
this.FromDateTimePicker.Size = new System.Drawing.Size(199, 27);
this.FromDateTimePicker.TabIndex = 1;
//
// FromLabel
//
this.FromLabel.AutoSize = true;
this.FromLabel.Location = new System.Drawing.Point(11, 13);
this.FromLabel.Name = "FromLabel";
this.FromLabel.Size = new System.Drawing.Size(18, 20);
this.FromLabel.TabIndex = 0;
this.FromLabel.Text = "C";
//
// FormReportOrders
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1105, 451);
this.Controls.Add(this.Panel);
this.Name = "FormReportOrders";
this.Text = "Заказы";
this.Panel.ResumeLayout(false);
this.Panel.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private Panel Panel;
private Button ToPdfButton;
private Button CreateButton;
private DateTimePicker ToDateTimePicker;
private Label ToLabel;
private DateTimePicker FromDateTimePicker;
private Label FromLabel;
}
}

View File

@ -0,0 +1,100 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
using Microsoft.Reporting.WinForms;
namespace BarView.Forms
{
public partial class FormReportOrders : Form
{
private readonly ReportViewer _reportViewer;
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportOrders(ILogger<FormReportOrders> Logger, IReportLogic Logic)
{
InitializeComponent();
_logger = Logger;
_logic = Logic;
_reportViewer = new ReportViewer
{
Dock = DockStyle.Fill
};
_reportViewer.LocalReport.LoadReportDefinition(new FileStream("ReportOrder.rdlc", FileMode.Open));
Controls.Clear();
Controls.Add(_reportViewer);
Controls.Add(Panel);
}
private void ButtonMake_Click(object sender, EventArgs e)
{
if (FromDateTimePicker.Value.Date >= ToDateTimePicker.Value.Date)
{
MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
var DataSource = _logic.GetOrders(new ReportBindingModel
{
DateFrom = FromDateTimePicker.Value,
DateTo = ToDateTimePicker.Value
});
var Source = new ReportDataSource("DataSetOrders", DataSource);
_reportViewer.LocalReport.DataSources.Clear();
_reportViewer.LocalReport.DataSources.Add(Source);
var Parameters = new[] {
new ReportParameter("ReportParameterPeriod", $"c {FromDateTimePicker.Value.ToShortDateString()} по {ToDateTimePicker.Value.ToShortDateString()}")
};
_reportViewer.LocalReport.SetParameters(Parameters);
_reportViewer.RefreshReport();
_logger.LogInformation("Загрузка списка заказов на период {From}-{To}", FromDateTimePicker.Value.ToShortDateString(), ToDateTimePicker.Value.ToShortDateString());
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonToPdf_Click(object sender, EventArgs e)
{
if (FromDateTimePicker.Value.Date >= ToDateTimePicker.Value.Date)
{
MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
using var Dialog = new SaveFileDialog { Filter = "pdf|*.pdf" };
if (Dialog.ShowDialog() == DialogResult.OK)
{
try
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
_logic.SaveOrdersToPdfFile(new ReportBindingModel
{
FileName = Dialog.FileName,
DateFrom = FromDateTimePicker.Value,
DateTo = ToDateTimePicker.Value
});
_logger.LogInformation("Сохранение списка заказов на период {From}-{To}", FromDateTimePicker.Value.ToShortDateString(), ToDateTimePicker.Value.ToShortDateString());
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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>

88
Bar/Bar/Program.cs Normal file
View File

@ -0,0 +1,88 @@
using BarBusinessLogic.BusinessLogics;
using BarBusinessLogic.OfficePackage.Implements;
using BarBusinessLogic.OfficePackage;
using BarContracts.BusinessLogicContracts;
using BarView.Forms;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using BarContracts.BusinessLogicsContracts;
using BarBusinessLogic.MailWorker;
using BarContracts.BindingModels;
using BarContracts.DI;
namespace BarView
{
internal static class Program
{
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
InitDependency();
try
{
var MailSender = DependencyManager.Instance.Resolve<AbstractMailWorker>();
MailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty,
SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty,
SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]),
PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty,
PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"])
});
var Timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000);
}
catch (Exception ex)
{
var Logger = DependencyManager.Instance.Resolve<ILogger>();
Logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé");
}
Application.Run(DependencyManager.Instance.Resolve<FormMain>());
}
private static void MailCheck(object obj) => DependencyManager.Instance.Resolve<AbstractMailWorker>()?.CheckMailAsync();
private static void InitDependency()
{
DependencyManager.InitDependency();
DependencyManager.Instance.AddLogging(Option =>
{
Option.SetMinimumLevel(LogLevel.Information);
Option.AddNLog("nlog.config");
});
DependencyManager.Instance.RegisterType<IComponentLogic, ComponentLogic>();
DependencyManager.Instance.RegisterType<IOrderLogic, OrderLogic>();
DependencyManager.Instance.RegisterType<ICocktailLogic, CocktailLogic>();
DependencyManager.Instance.RegisterType<IReportLogic, ReportLogic>();
DependencyManager.Instance.RegisterType<IClientLogic, ClientLogic>();
DependencyManager.Instance.RegisterType<IImplementerLogic, ImplementerLogic>();
DependencyManager.Instance.RegisterType<IWorkProcess, WorkModeling>();
DependencyManager.Instance.RegisterType<IMessageInfoLogic, MessageInfoLogic>();
DependencyManager.Instance.RegisterType<IBackUpLogic, BackUpLogic>();
DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
DependencyManager.Instance.RegisterType<AbstractSaveToPdf, SaveToPdf>();
DependencyManager.Instance.RegisterType<AbstractMailWorker, MailKitWorker>(true);
DependencyManager.Instance.RegisterType<FormMain>();
DependencyManager.Instance.RegisterType<FormComponent>();
DependencyManager.Instance.RegisterType<FormComponents>();
DependencyManager.Instance.RegisterType<FormCreateOrder>();
DependencyManager.Instance.RegisterType<FormCocktail>();
DependencyManager.Instance.RegisterType<FormCocktailComponent>();
DependencyManager.Instance.RegisterType<FormCocktails>();
DependencyManager.Instance.RegisterType<FormReportCocktailComponents>();
DependencyManager.Instance.RegisterType<FormReportOrders>();
DependencyManager.Instance.RegisterType<FormClients>();
DependencyManager.Instance.RegisterType<FormImplementers>();
DependencyManager.Instance.RegisterType<FormImplementer>();
DependencyManager.Instance.RegisterType<FormMail>();
}
}
}

120
Bar/Bar/Program.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

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio .Net. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="IComponentLogic" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>BarContracts.BusinessLogicContracts.IComponentLogic, BarContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio .Net. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="IOrderLogic" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>BarContracts.BusinessLogicContracts.IOrderLogic, BarContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio .Net. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="ICocktailStorage" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>BarContracts.StoragesContracts.ICocktailStorage, BarContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio .Net. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="IComponentStorage" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>BarContracts.StoragesContracts.IComponentStorage, BarContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio .Net. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="IOrderStorage" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>BarContracts.StoragesContracts.IOrderStorage, BarContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

572
Bar/Bar/ReportOrder.rdlc Normal file
View File

@ -0,0 +1,572 @@
<?xml version="1.0" encoding="utf-8"?>
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
<AutoRefresh>0</AutoRefresh>
<DataSources>
<DataSource Name="BarContractsViewModels">
<ConnectionProperties>
<DataProvider>System.Data.DataSet</DataProvider>
<ConnectString>/* Local Connection */</ConnectString>
</ConnectionProperties>
<rd:DataSourceID>10791c83-cee8-4a38-bbd0-245fc17cefb3</rd:DataSourceID>
</DataSource>
</DataSources>
<DataSets>
<DataSet Name="DataSetOrders">
<Query>
<DataSourceName>BarContractsViewModels</DataSourceName>
<CommandText>/* Local Query */</CommandText>
</Query>
<Fields>
<Field Name="Id">
<DataField>Id</DataField>
<rd:TypeName>System.Int32</rd:TypeName>
</Field>
<Field Name="DateCreate">
<DataField>DateCreate</DataField>
<rd:TypeName>System.DateTime</rd:TypeName>
</Field>
<Field Name="CocktailName">
<DataField>CocktailName</DataField>
<rd:TypeName>System.String</rd:TypeName>
</Field>
<Field Name="Sum">
<DataField>Sum</DataField>
<rd:TypeName>System.Decimal</rd:TypeName>
</Field>
<Field Name="Status">
<DataField>Status</DataField>
<rd:TypeName>System.String</rd:TypeName>
</Field>
</Fields>
<rd:DataSetInfo>
<rd:DataSetName>BarContracts.ViewModels</rd:DataSetName>
<rd:TableName>ReportOrdersViewModel</rd:TableName>
<rd:ObjectDataSourceType>BarContracts.ViewModels.ReportOrdersViewModel, BarContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</rd:ObjectDataSourceType>
</rd:DataSetInfo>
</DataSet>
</DataSets>
<ReportSections>
<ReportSection>
<Body>
<ReportItems>
<Textbox Name="TextboxTitle">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Заказы</Value>
<Style />
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Height>0.6cm</Height>
<Width>22.058cm</Width>
<Style>
<Border>
<Style>None</Style>
</Border>
<VerticalAlign>Middle</VerticalAlign>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Textbox Name="ReportParameterPeriod">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Parameters!ReportParameterPeriod.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<rd:DefaultName>ReportParameterPeriod</rd:DefaultName>
<Top>0.6cm</Top>
<Height>0.6cm</Height>
<Width>22.058cm</Width>
<ZIndex>1</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<VerticalAlign>Middle</VerticalAlign>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Tablix Name="Tablix">
<TablixBody>
<TablixColumns>
<TablixColumn>
<Width>2.60583cm</Width>
</TablixColumn>
<TablixColumn>
<Width>5.27517cm</Width>
</TablixColumn>
<TablixColumn>
<Width>6.1195cm</Width>
</TablixColumn>
<TablixColumn>
<Width>4.76483cm</Width>
</TablixColumn>
<TablixColumn>
<Width>2.5cm</Width>
</TablixColumn>
</TablixColumns>
<TablixRows>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="TextboxId">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Номер</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="TextboxDateCreate">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Дата создания</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="TextboxCocktailName">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Коктейль</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Textbox2">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Статус</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox2</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="TextboxSum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Сумма</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
</TablixCells>
</TablixRow>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="Id">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!Id.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Id</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="DateCreate">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!DateCreate.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>DateCreate</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="CocktailName">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!CocktailName.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>CocktailName</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Status1">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!Status.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Status1</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Sum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!Sum.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Sum</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
</TablixCells>
</TablixRow>
</TablixRows>
</TablixBody>
<TablixColumnHierarchy>
<TablixMembers>
<TablixMember />
<TablixMember />
<TablixMember />
<TablixMember />
<TablixMember />
</TablixMembers>
</TablixColumnHierarchy>
<TablixRowHierarchy>
<TablixMembers>
<TablixMember>
<KeepWithGroup>After</KeepWithGroup>
</TablixMember>
<TablixMember>
<Group Name="Подробности" />
</TablixMember>
</TablixMembers>
</TablixRowHierarchy>
<DataSetName>DataSetOrders</DataSetName>
<Top>1.9177cm</Top>
<Left>0.79267cm</Left>
<Height>1.2cm</Height>
<Width>21.26533cm</Width>
<ZIndex>2</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
</Style>
</Tablix>
<Textbox Name="TextboxResout">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Итого:</Value>
<Style />
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>3.46287cm</Top>
<Left>16.61349cm</Left>
<Height>0.6cm</Height>
<Width>2.5cm</Width>
<ZIndex>3</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Textbox Name="Textbox10">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Sum(Fields!Sum.Value, "DataSetOrders")</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox10</rd:DefaultName>
<Top>3.46287cm</Top>
<Left>19.11349cm</Left>
<Height>0.6cm</Height>
<Width>2.5cm</Width>
<ZIndex>4</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</ReportItems>
<Height>2in</Height>
<Style />
</Body>
<Width>8.68425in</Width>
<Page>
<PageHeight>29.7cm</PageHeight>
<PageWidth>21cm</PageWidth>
<LeftMargin>2cm</LeftMargin>
<RightMargin>2cm</RightMargin>
<TopMargin>2cm</TopMargin>
<BottomMargin>2cm</BottomMargin>
<ColumnSpacing>0.13cm</ColumnSpacing>
<Style />
</Page>
</ReportSection>
</ReportSections>
<ReportParameters>
<ReportParameter Name="ReportParameterPeriod">
<DataType>String</DataType>
<Nullable>true</Nullable>
<Prompt>ReportParameter1</Prompt>
</ReportParameter>
</ReportParameters>
<ReportParametersLayout>
<GridLayoutDefinition>
<NumberOfColumns>4</NumberOfColumns>
<NumberOfRows>2</NumberOfRows>
<CellDefinitions>
<CellDefinition>
<ColumnIndex>0</ColumnIndex>
<RowIndex>0</RowIndex>
<ParameterName>ReportParameterPeriod</ParameterName>
</CellDefinition>
</CellDefinitions>
</GridLayoutDefinition>
</ReportParametersLayout>
<rd:ReportUnitType>Cm</rd:ReportUnitType>
<rd:ReportID>0c9e94bc-df40-42bd-a526-01713dd3057f</rd:ReportID>
</Report>

9
Bar/Bar/nlog.config Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog throwExceptions="true">
<targets>
<target name="file" type="File" fileName="${basedir}/log.txt" />
</targets>
<rules>
<logger name="*" minLevel="Trace" writeTo="file" />
</rules>
</nlog>

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.1.32210.238
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BarBusinessLogic", "BarBusinessLogic\BarBusinessLogic.csproj", "{1D8E732A-3606-4D9D-93C3-B462140CCD42}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BarContracts", "..\BarContracts\BarContracts\BarContracts.csproj", "{4F98835A-6D71-4F8C-A54B-65EA47207D69}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1D8E732A-3606-4D9D-93C3-B462140CCD42}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1D8E732A-3606-4D9D-93C3-B462140CCD42}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1D8E732A-3606-4D9D-93C3-B462140CCD42}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1D8E732A-3606-4D9D-93C3-B462140CCD42}.Release|Any CPU.Build.0 = Release|Any CPU
{4F98835A-6D71-4F8C-A54B-65EA47207D69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4F98835A-6D71-4F8C-A54B-65EA47207D69}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4F98835A-6D71-4F8C-A54B-65EA47207D69}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4F98835A-6D71-4F8C-A54B-65EA47207D69}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C7A22A4A-209E-46CA-AFC1-B5E2138647CB}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net6.0-windows</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.19.0" />
<PackageReference Include="MailKit" Version="4.6.0" />
<PackageReference Include="NLog" Version="5.3.2" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
<PackageReference Include="ReportViewerCore.WinForms" Version="15.1.19" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\BarContracts\BarContracts\BarContracts.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="OfficePackage\HelperModels\" />
</ItemGroup>
<ItemGroup>
<Content Include="foldername\**" CopyToPublishDirectory="Always" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,100 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.StoragesContracts;
using BarDataModels.Models;
using Microsoft.Extensions.Logging;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.Serialization.Json;
namespace BarBusinessLogic.BusinessLogics
{
public class BackUpLogic : IBackUpLogic
{
private readonly ILogger _logger;
private readonly IBackUpInfo _backUpInfo;
public BackUpLogic(ILogger<BackUpLogic> Logger, IBackUpInfo BackUpInfo)
{
_logger = Logger;
_backUpInfo = BackUpInfo;
}
public void CreateBackUp(BackUpSaveBindingModel Model)
{
if (_backUpInfo == null)
return;
try
{
_logger.LogDebug("Clear folder");
var DirInfo = new DirectoryInfo(Model.FolderName);
if (DirInfo.Exists)
{
foreach (var File in DirInfo.GetFiles())
{
File.Delete();
}
}
_logger.LogDebug("Delete archive");
string FileName = $"{Model.FolderName}.zip";
if (File.Exists(FileName))
{
File.Delete(FileName);
}
_logger.LogDebug("Get assembly");
var TypeIId = typeof(IId);
var Assembly = TypeIId.Assembly;
if (Assembly == null)
{
throw new ArgumentNullException("Сборка не найдена", nameof(Assembly));
}
var Types = Assembly.GetTypes();
var Method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance);
_logger.LogDebug("Found {count} types", Types.Length);
foreach (var Type in Types)
{
if (Type.IsInterface && Type.GetInterface(TypeIId.Name) != null)
{
var ModelType = _backUpInfo.GetTypeByModelInterface(Type.Name);
if (ModelType == null)
{
throw new InvalidOperationException($"Не найден класс - модель для { Type.Name }");
}
_logger.LogDebug("Call SaveToFile method for {name} Type", Type.Name);
Method?.MakeGenericMethod(ModelType).Invoke(this, new object[] { Model.FolderName });
}
}
_logger.LogDebug("Create zip and remove folder");
ZipFile.CreateFromDirectory(Model.FolderName, FileName);
DirInfo.Delete(true);
}
catch (Exception)
{
throw;
}
}
private void SaveToFile<T>(string FolderName) where T : class, new()
{
var Records = _backUpInfo.GetList<T>();
if (Records == null)
{
_logger.LogWarning("{type} type get null list", typeof(T).Name);
return;
}
var JsonFormatter = new DataContractJsonSerializer(typeof(List<T>));
using var fs = new FileStream(string.Format("{0}/{1}.json", FolderName, typeof(T).Name), FileMode.OpenOrCreate);
JsonFormatter.WriteObject(fs, Records);
}
}
}

View File

@ -0,0 +1,121 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.SearchModels;
using BarContracts.StoragesContracts;
using BarContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace BarBusinessLogic.BusinessLogics
{
public class ClientLogic : IClientLogic
{
private readonly ILogger _logger;
private readonly IClientStorage _clientStorage;
public ClientLogic(ILogger<ClientLogic> Logger, IClientStorage ClientStorage)
{
_logger = Logger;
_clientStorage = ClientStorage;
}
public List<ClientViewModel>? ReadList(ClientSearchModel? Model)
{
_logger.LogInformation("ReadList. ClientFIO: {ClientFIO}. Id: {Id}", Model?.ClientFIO, Model?.Id);
var List = Model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(Model);
if (List == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count: {Count}", List.Count);
return List;
}
public ClientViewModel? ReadElement(ClientSearchModel Model)
{
if (Model == null)
throw new ArgumentNullException(nameof(Model));
_logger.LogInformation("ReadElement. ClientFIO: {ClientFIO}.Id: {Id}", Model.ClientFIO, Model.Id);
ClientViewModel? Client = _clientStorage.GetElement(Model);
if (Client == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id: {Id}", Client.Id);
return Client;
}
public bool Create(ClientBindingModel Model)
{
CheckModel(Model);
if (_clientStorage.Insert(Model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ClientBindingModel Model)
{
CheckModel(Model);
if (_clientStorage.Update(Model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ClientBindingModel Model)
{
CheckModel(Model, false);
_logger.LogInformation("Delete. Id:{Id}", Model.Id);
if (_clientStorage.Delete(Model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ClientBindingModel Model, bool WithParams=true)
{
if (Model == null)
throw new ArgumentNullException(nameof(Model));
if (!WithParams)
if (string.IsNullOrEmpty(Model.ClientFIO))
throw new ArgumentNullException("Нет ФИО клиента", nameof(Model.ClientFIO));
if (string.IsNullOrEmpty(Model.Email))
throw new ArgumentNullException("Нет Email клиента", nameof(Model.ClientFIO));
if (string.IsNullOrEmpty(Model.Password))
throw new ArgumentNullException("Нет пароля клиента", nameof(Model.ClientFIO));
_logger.LogInformation("Client. ClientFIO: {ClientFIO}." +
"Email: {Email}. Password: {Password}. Id: {Id} ", Model.ClientFIO, Model.Email, Model.Password, Model.Id);
ClientViewModel? Client = _clientStorage.GetElement(new ClientSearchModel
{
Email = Model.Email,
});
if (Client != null && Client.Id != Model.Id)
throw new InvalidOperationException("Клиент с таким логином уже есть");
}
}
}

View File

@ -0,0 +1,126 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.SearchModels;
using BarContracts.StoragesContracts;
using BarContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace BarBusinessLogic.BusinessLogics
{
public class CocktailLogic : ICocktailLogic
{
private readonly ILogger _logger;
private readonly ICocktailStorage _cocktailStorage;
public CocktailLogic(ILogger<CocktailLogic> Logger, ICocktailStorage CocktailStorage)
{
_logger = Logger;
_cocktailStorage = CocktailStorage;
}
public List<CocktailViewModel>? ReadList(CocktailSearchModel? Model)
{
_logger.LogInformation("ReadList. CocktailName:{CocktailName}. Id:{Id}",
Model?.CocktailName, Model?.Id);
var List = Model is null ? _cocktailStorage.GetFullList() : _cocktailStorage.GetFilteredList(Model);
if (List is null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", List.Count);
return List;
}
public CocktailViewModel? ReadElement(CocktailSearchModel? Model)
{
if (Model is null)
throw new ArgumentNullException(nameof(Model));
_logger.LogInformation("ReadElement. CocktailName:{CocktailName}. Id:{Id}",
Model.CocktailName, Model.Id);
var Element = _cocktailStorage.GetElement(Model);
if (Element is null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement element found. Id:{Id}", Element.Id);
return Element;
}
public bool Create(CocktailBindingModel Model)
{
CheckModel(Model);
if (_cocktailStorage.Insert(Model) is null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(CocktailBindingModel Model)
{
CheckModel(Model);
if (_cocktailStorage.Update(Model) is null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(CocktailBindingModel Model)
{
CheckModel(Model);
_logger.LogInformation("Delete. Id:{Id}", Model.Id);
if (_cocktailStorage.Delete(Model) is null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(CocktailBindingModel Model, bool WithParams = true)
{
if (Model == null)
throw new ArgumentNullException(nameof(Model));
if (!WithParams)
return;
if (string.IsNullOrEmpty(Model.CocktailName))
throw new ArgumentNullException("Нет названия коктеля", nameof(Model.CocktailName));
if (Model.Price <= 0)
throw new ArgumentNullException("Стоимость коктеля должна быть больше 0", nameof(Model.Price));
_logger.LogInformation("Cocktail. CocktailName:{CocktailName}. Price:{Price}. Id: {Id}",
Model.CocktailName, Model.Price, Model.Id);
var Element = _cocktailStorage.GetElement(new CocktailSearchModel
{
CocktailName = Model.CocktailName
});
if (Element != null && Element.Id != Model.Id)
throw new InvalidOperationException("Коктель с таким названием уже есть");
}
}
}

View File

@ -0,0 +1,125 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.SearchModels;
using BarContracts.StoragesContracts;
using BarContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace BarBusinessLogic.BusinessLogics
{
public class ComponentLogic : IComponentLogic
{
private readonly ILogger _logger;
private readonly IComponentStorage _componentStorage;
public ComponentLogic(ILogger<ComponentLogic> Logger, IComponentStorage ComponentStorage)
{
_logger = Logger;
_componentStorage = ComponentStorage;
}
public List<ComponentViewModel>? ReadList(ComponentSearchModel? Model)
{
_logger.LogInformation("ReadList. ComponentName:{ComponentName}. Id:{Id}",
Model?.ComponentName, Model?.Id);
var List = Model is null ? _componentStorage.GetFullList() : _componentStorage.GetFilteredList(Model);
if (List is null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", List.Count);
return List;
}
public ComponentViewModel? ReadElement(ComponentSearchModel? Model)
{
if (Model is null)
throw new ArgumentNullException(nameof(Model));
_logger.LogInformation("ReadElement. ComponentName:{ComponentName}. Id:{Id}",
Model.ComponentName, Model.Id);
var Element = _componentStorage.GetElement(Model);
if (Element is null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement element found. Id:{Id}", Element.Id);
return Element;
}
public bool Create(ComponentBindingModel Model)
{
CheckModel(Model);
if (_componentStorage.Insert(Model) is null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ComponentBindingModel Model)
{
CheckModel(Model);
if (_componentStorage.Update(Model) is null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ComponentBindingModel Model)
{
CheckModel(Model, false);
_logger.LogInformation("Delete. Id:{Id}", Model.Id);
if (_componentStorage.Delete(Model) is null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ComponentBindingModel Model, bool WithParams = true)
{
if (Model == null)
throw new ArgumentNullException(nameof(Model));
if (!WithParams)
return;
if (string.IsNullOrEmpty(Model.ComponentName))
throw new ArgumentNullException("Нет названия компонента", nameof(Model.ComponentName));
if (Model.Cost <= 0)
throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(Model.Cost));
_logger.LogInformation("Cocktail. ComponentName:{ComponentName}. Cost:{Cost}. Id:{Id}",
Model.ComponentName, Model.Cost, Model.Id);
var Element = _componentStorage.GetElement(new ComponentSearchModel
{
ComponentName = Model.ComponentName
});
if (Element != null && Element.Id != Model.Id)
throw new InvalidOperationException("Компонент с таким названием уже есть");
}
}
}

View File

@ -0,0 +1,135 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicsContracts;
using BarContracts.SearchModels;
using BarContracts.StoragesContracts;
using BarContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace BarBusinessLogic.BusinessLogics
{
public class ImplementerLogic : IImplementerLogic
{
private readonly ILogger _logger;
private readonly IImplementerStorage _implementerStorage;
public ImplementerLogic(ILogger<IImplementerLogic> Logger, IImplementerStorage ImplementerStorage)
{
_logger = Logger;
_implementerStorage = ImplementerStorage;
}
public List<ImplementerViewModel>? ReadList(ImplementerSearchModel? Model)
{
_logger.LogInformation("ReadList. ImplementerFIO: {ImplementerFIO}. Password: {Password}. Id: {Id}",
Model?.ImplementerFIO, Model?.Password?.Length, Model?.Id);
var List = Model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(Model);
if (List == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count: {Count}", List.Count);
return List;
}
public ImplementerViewModel? ReadElement(ImplementerSearchModel Model)
{
if (Model is null)
{
throw new ArgumentNullException(nameof(Model));
}
_logger.LogInformation("ReadElement. ImplementerFIO: {ImplementerFIO}. Password: {Password}. Id: {Id}",
Model?.ImplementerFIO, Model?.Password?.Length, Model?.Id);
var Element = _implementerStorage.GetElement(Model);
if (Element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id: {Id}", Element.Id);
return Element;
}
public bool Create(ImplementerBindingModel Model)
{
CheckModel(Model);
if (_implementerStorage.Insert(Model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ImplementerBindingModel Model)
{
CheckModel(Model);
if (_implementerStorage.Update(Model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ImplementerBindingModel Model)
{
CheckModel(Model, false);
_logger.LogInformation("Delete. Id:{Id}", Model.Id);
if (_implementerStorage.Delete(Model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ImplementerBindingModel Model, bool WithParams = true)
{
if (Model == null)
throw new ArgumentNullException(nameof(Model));
if (!WithParams)
return;
if (string.IsNullOrEmpty(Model.ImplementerFIO))
throw new ArgumentNullException("Нет ФИО исполнителя", nameof(Model.ImplementerFIO));
if (string.IsNullOrEmpty(Model.Password))
throw new ArgumentNullException("Нет пароля исполнителя", nameof(Model.Password));
if (Model.WorkExperience < 0)
throw new ArgumentNullException("Стаж должен быть неотрицательным целым числом", nameof(Model.WorkExperience));
if (Model.Qualification < 0)
throw new ArgumentNullException("Квалификация должна быть неотрицательным целым числом", nameof(Model.Qualification));
_logger.LogInformation("Implementer. ImplementerFIO: {ImplementerFIO}. Password: {Password}. WorkExperience: {WorkExperience}. Qualification: {Qualification}. Id: {Id}",
Model.ImplementerFIO, Model.Password, Model.WorkExperience, Model.Qualification, Model.Id);
var Implementer = _implementerStorage.GetElement(new ImplementerSearchModel
{
ImplementerFIO = Model.ImplementerFIO
});
if (Implementer != null && Implementer.Id != Model.Id)
{
throw new InvalidOperationException("Исполнитель с таким ФИО уже есть");
}
}
}
}

View File

@ -0,0 +1,88 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.SearchModels;
using BarContracts.StoragesContracts;
using BarContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace BarBusinessLogic.BusinessLogics
{
public class MessageInfoLogic : IMessageInfoLogic
{
private readonly ILogger _logger;
private readonly IMessageInfoStorage _messageInfoStorage;
private readonly IClientStorage _clientStorage;
public MessageInfoLogic(ILogger<MessageInfoLogic> Logger, IMessageInfoStorage MessageInfoStorage, IClientStorage ClientStorage)
{
_logger = Logger;
_messageInfoStorage = MessageInfoStorage;
_clientStorage = ClientStorage;
}
public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? Model)
{
_logger.LogDebug("ReadList. MessageId: {MessageId}, ClientId: {ClientId}", Model?.MessageId, Model?.ClientId);
var Result = Model == null ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(Model);
_logger.LogDebug("ReadList result. Count: {Count}", Result.Count);
return Result;
}
public bool Create(MessageInfoBindingModel Model)
{
try {
CheckModel(Model);
if (_messageInfoStorage.Insert(Model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
}
catch { }
return true;
}
private void CheckModel(MessageInfoBindingModel Model, bool WithParams = true)
{
if (Model == null)
throw new ArgumentNullException(nameof(Model));
if (!WithParams)
return;
if (string.IsNullOrEmpty(Model.MessageId))
throw new ArgumentNullException("Не указан id сообщения", nameof(Model.MessageId));
if (string.IsNullOrEmpty(Model.SenderName))
throw new ArgumentNullException("Не указао почта", nameof(Model.SenderName));
if (string.IsNullOrEmpty(Model.Subject))
throw new ArgumentNullException("Не указана тема", nameof(Model.Subject));
if (string.IsNullOrEmpty(Model.Body))
throw new ArgumentNullException("Не указан текст сообщения", nameof(Model.Subject));
_logger.LogInformation("MessageInfo. MessageId: {MessageId}. SenderName: {SenderName}. Subject: {Subject}. Body: {Body}",
Model.MessageId, Model.SenderName, Model.Subject, Model.Body);
var Element = _clientStorage.GetElement(new ClientSearchModel
{
Email = Model.SenderName
});
if (Element == null)
{
_logger.LogWarning("Не удалось найти клиента, отправившего письмо с адреса {Email}", Model.SenderName);
}
else
{
Model.ClientId = Element.Id;
}
}
}
}

View File

@ -0,0 +1,181 @@
using BarBusinessLogic.MailWorker;
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.SearchModels;
using BarContracts.StoragesContracts;
using BarContracts.ViewModels;
using BarDataModels.Enums;
using Microsoft.Extensions.Logging;
namespace BarBusinessLogic.BusinessLogics
{
public class OrderLogic : IOrderLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
private readonly AbstractMailWorker _mailLogic;
static readonly object _locker = new object();
public OrderLogic(ILogger<CocktailLogic> Logger, IOrderStorage OrderStorage, AbstractMailWorker MailLogic)
{
_logger = Logger;
_orderStorage = OrderStorage;
_mailLogic = MailLogic;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? Model)
{
_logger.LogInformation("ReadList. ClientId: {ClientId}. Status: {Status}. ImplementerId: {ImplementerId}. DateFrom: {DateFrom}. DateTo: {DateTo}. OrderId: {Id}",
Model?.ClientId, Model?.Status, Model?.ImplementerId, Model?.DateFrom, Model?.DateTo, Model?.Id);
var List = Model is null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(Model);
if (List is null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count: {Count}", List.Count);
return List;
}
public bool CreateOrder(OrderBindingModel Model)
{
CheckModel(Model);
if (Model.Status != OrderStatus.Undefined)
{
_logger.LogWarning("Invalid order status");
return false;
}
Model.Status = OrderStatus.Accepted;
var CreatedOrder = _orderStorage.Insert(Model);
if (CreatedOrder == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
Task.Run(() => _mailLogic.SendMailAsync(new MailSendInfoBindingModel
{
MailAddress = CreatedOrder.ClientEmail,
Subject = $"Изменение статуса заказа номер {CreatedOrder.Id}",
Text = $"Ваш заказ номер {CreatedOrder.Id} на коктейль {CreatedOrder.CocktailName} от {CreatedOrder.DateCreate} на сумму {CreatedOrder.Sum} принят."
}));
return true;
}
private bool ChangeOrderStatus(OrderBindingModel Model, OrderStatus NewStatus)
{
CheckModel(Model, false);
var Order = _orderStorage.GetElement(new OrderSearchModel { Id = Model.Id });
if (Order == null)
{
_logger.LogWarning("Change status operation failed. Order not found");
return false;
}
if (Order.Status + 1 != NewStatus)
{
_logger.LogWarning("Change status operation failed. Incorrect new status: {NewStatus}. Current status: {currStatus}",
NewStatus, Order.Status);
return false;
}
Model.CocktailId = Order.CocktailId;
Model.ClientId = Order.ClientId;
if (!Model.ImplementerId.HasValue) Model.ImplementerId = Order.ImplementerId;
Model.Count = Order.Count;
Model.Sum = Order.Sum;
Model.DateCreate = Order.DateCreate;
Model.Status = NewStatus;
if (Model.Status == OrderStatus.Ready)
Model.DateImplement = DateTime.Now;
else
Model.DateImplement = Order.DateImplement;
if (_orderStorage.Update(Model) == null)
{
_logger.LogWarning("Change status operation failed");
return false;
}
string DateInfo = Model.DateImplement.HasValue ? $"Дата выполнения: {Model.DateImplement}" : "";
Task.Run(() => _mailLogic.SendMailAsync(new MailSendInfoBindingModel
{
MailAddress = Order.ClientEmail,
Subject = $"Изменение статуса заказа номер {Order.Id}",
Text = $"Ваш заказ номер {Order.Id} на коктейль {Order.CocktailName} от {Order.DateCreate} на сумму {Order.Sum}. Статус изменен на {NewStatus}. {DateInfo}"
}));
return true;
}
public bool TakeOrderInWork(OrderBindingModel Model)
{
lock (_locker)
{
return ChangeOrderStatus(Model, OrderStatus.BeingProcessed);
}
}
public bool FinishOrder(OrderBindingModel Model)
{
return ChangeOrderStatus(Model, OrderStatus.Ready);
}
public bool DeliveryOrder(OrderBindingModel Model)
{
return ChangeOrderStatus(Model, OrderStatus.Delivered);
}
private void CheckModel(OrderBindingModel Model, bool WithParams = true)
{
if (Model == null)
throw new ArgumentNullException(nameof(Model));
if (!WithParams)
return;
if (Model.Count <= 0)
throw new ArgumentNullException("Количество коктейльов в заказе быть больше 0", nameof(Model.Count));
if (Model.Sum <= 0)
throw new ArgumentNullException("Стоимость заказа должна быть больше 0", nameof(Model.Sum));
_logger.LogInformation("Order. CocktailId:{CocktailId}. Count:{Count}. Sum:{Sum}. " +
"Status:{Status}. DateCreate:{DateCreate}. DateImplement:{DateImplement}. Id: {Id}",
Model.CocktailId, Model.Count, Model.Sum, Model.Status, Model.DateCreate,
Model.DateImplement, Model.Id);
}
public OrderViewModel? ReadElement(OrderSearchModel Model)
{
if (Model == null)
{
throw new ArgumentNullException(nameof(Model));
}
_logger.LogInformation("ReadElement. ClientId: {ClientId}. Status: {Status}. ImplementerId: {ImplementerId}. DateFrom: {DateFrom}. DateTo: {DateTo}. OrderId: {Id}",
Model.ClientId, Model.Status, Model.ImplementerId, Model.DateFrom, Model.DateTo, Model.Id);
var Order = _orderStorage.GetElement(Model);
if (Order == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id: {Id}", Order.Id);
return Order;
}
}
}

View File

@ -0,0 +1,90 @@
using BarBusinessLogic.OfficePackage;
using BarBusinessLogic.OfficePackage.HelperModels;
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.SearchModels;
using BarContracts.StoragesContracts;
using BarContracts.ViewModels;
namespace BarBusinessLogic.BusinessLogics
{
public class ReportLogic : IReportLogic
{
private readonly IComponentStorage _componentStorage;
private readonly ICocktailStorage _CocktailStorage;
private readonly IOrderStorage _orderStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(ICocktailStorage CocktailStorage, IComponentStorage ComponentStorage, IOrderStorage OrderStorage,
AbstractSaveToExcel SaveToExcel, AbstractSaveToWord SaveToWord, AbstractSaveToPdf SaveToPdf)
{
_CocktailStorage = CocktailStorage;
_componentStorage = ComponentStorage;
_orderStorage = OrderStorage;
_saveToExcel = SaveToExcel;
_saveToWord = SaveToWord;
_saveToPdf = SaveToPdf;
}
public List<ReportCocktailComponentViewModel> GetCocktailComponents()
{
return _CocktailStorage.GetFullList().
Select(x => new ReportCocktailComponentViewModel
{
CocktailName = x.CocktailName,
Components = x.CocktailComponents.Select(x => (x.Value.Item1.ComponentName, x.Value.Item2)).ToList(),
TotalCount = x.CocktailComponents.Select(x => x.Value.Item2).Sum()
})
.ToList();
}
public List<ReportOrdersViewModel> GetOrders(ReportBindingModel Model)
{
return _orderStorage.GetFilteredList(new OrderSearchModel { DateFrom = Model.DateFrom, DateTo = Model.DateTo })
.Select(x => new ReportOrdersViewModel
{
Id = x.Id,
DateCreate = x.DateCreate,
CocktailName = x.CocktailName,
Sum = x.Sum,
Status = x.Status.ToString()
})
.ToList();
}
public void SaveComponentsToWordFile(ReportBindingModel Model)
{
_saveToWord.CreateDoc(new WordInfo
{
FileName = Model.FileName,
Title = "Список Коктейлей",
Cocktails = _CocktailStorage.GetFullList()
});
}
public void SaveCocktailComponentToExcelFile(ReportBindingModel Model)
{
_saveToExcel.CreateReport(new ExcelInfo
{
FileName = Model.FileName,
Title = "Список компонентов",
CocktailComponents = GetCocktailComponents()
});
}
public void SaveOrdersToPdfFile(ReportBindingModel Model)
{
_saveToPdf.CreateDoc(new PdfInfo
{
FileName = Model.FileName,
Title = "Список заказов",
DateFrom = Model.DateFrom!.Value,
DateTo = Model.DateTo!.Value,
Orders = GetOrders(Model)
});
}
}
}

View File

@ -0,0 +1,153 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.BusinessLogicsContracts;
using BarContracts.SearchModels;
using BarContracts.ViewModels;
using BarDataModels.Enums;
using Microsoft.Extensions.Logging;
namespace BarBusinessLogic.BusinessLogics
{
public class WorkModeling : IWorkProcess
{
private readonly ILogger _logger;
private readonly Random _rnd;
private IOrderLogic? _orderLogic;
public WorkModeling(ILogger<WorkModeling> Logger)
{
_logger = Logger;
_rnd = new Random(1000);
}
public void DoWork(IImplementerLogic ImplementerLogic, IOrderLogic OrderLogic)
{
_orderLogic = OrderLogic;
var Implementers = ImplementerLogic.ReadList(null);
if (Implementers == null)
{
_logger.LogWarning("DoWork. Implementers is null");
return;
}
var Orders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Accepted });
var BeingProcessedOrders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.BeingProcessed });
// in case there are BeingProcessed orders but no Accepted orders
if (Orders == null || BeingProcessedOrders == null || (Orders.Count == 0 && BeingProcessedOrders.Count == 0))
{
_logger.LogWarning("DoWork. Orders is null or empty");
return;
}
_logger.LogDebug("DoWork for {Count} orders", Orders.Count);
foreach (var Implementer in Implementers)
{
Task.Run(() => WorkerWorkAsync(Implementer, Orders));
}
}
private async Task WorkerWorkAsync(ImplementerViewModel Implementer, List<OrderViewModel> Orders)
{
if (_orderLogic == null || Implementer == null)
{
return;
}
await RunOrderInWork(Implementer);
await Task.Run(() =>
{
foreach (var Order in Orders)
{
try
{
_logger.LogDebug("WorkerWorkAsync. Worker {Id} try get order {Order}", Implementer.Id, Order.Id);
// TakeOrderInWork will fail when the worker tries to change status to BeingProcessed when the order is already BeingProcessed
// which would happen when other worker already acquired that order
bool AcquireResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = Order.Id,
ImplementerId = Implementer.Id
});
if (!AcquireResult)
{
_logger.LogDebug("WorkerWorkAsync. Worker {Id} tried to get order {Order} but it's already acquired by other worker", Implementer.Id, Order.Id);
continue;
}
Thread.Sleep(Implementer.WorkExperience * _rnd.Next(100, 1000) * Order.Count);
_logger.LogDebug("WorkerWorkAsync. Worker {Id} finish order {Order}", Implementer.Id, Order.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = Order.Id
});
}
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
Thread.Sleep(Implementer.Qualification * _rnd.Next(10, 100));
}
});
}
private async Task RunOrderInWork(ImplementerViewModel Implementer)
{
if (_orderLogic == null || Implementer == null)
return;
try
{
var RunOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel
{
ImplementerId = Implementer.Id,
Status = OrderStatus.BeingProcessed
}));
if (RunOrder == null)
{
return;
}
_logger.LogDebug("RunOrderInWork. Worker {Id} back to order {Order}", Implementer.Id, RunOrder.Id);
Thread.Sleep(Implementer.WorkExperience * _rnd.Next(100, 300) * RunOrder.Count);
_logger.LogDebug("RunOrderInWork. Worker {Id} finish order {Order}", Implementer.Id, RunOrder.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = RunOrder.Id
});
Thread.Sleep(Implementer.Qualification * _rnd.Next(10, 100));
}
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
}
}

View File

@ -0,0 +1,84 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
namespace BarBusinessLogic.MailWorker
{
public abstract class AbstractMailWorker
{
protected string _mailLogin = string.Empty;
protected string _mailPassword = string.Empty;
protected string _smtpClientHost = string.Empty;
protected int _smtpClientPort;
protected string _popHost = string.Empty;
protected int _popPort;
private readonly IMessageInfoLogic _messageInfoLogic;
private readonly ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> Logger, IMessageInfoLogic MessageInfoLogic)
{
_logger = Logger;
_messageInfoLogic = MessageInfoLogic;
}
public void MailConfig(MailConfigBindingModel Config)
{
_mailLogin = Config.MailLogin;
_mailPassword = Config.MailPassword;
_smtpClientHost = Config.SmtpClientHost;
_smtpClientPort = Config.SmtpClientPort;
_popHost = Config.PopHost;
_popPort = Config.PopPort;
_logger.LogDebug("MailConfig: {Login}, {Password}, {ClientHost}, {ClientPort}, {PopHost}, {PopPort}",
_mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort);
}
public async void SendMailAsync(MailSendInfoBindingModel Info)
{
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
return;
if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0)
return;
if (string.IsNullOrEmpty(Info.MailAddress) || string.IsNullOrEmpty(Info.Subject) || string.IsNullOrEmpty(Info.Text))
return;
_logger.LogDebug("MailSendAsync: {To}, {Subject}", Info.MailAddress, Info.Subject);
await SendMailImpl(Info);
}
public async void CheckMailAsync()
{
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
return;
if (string.IsNullOrEmpty(_popHost) || _popPort == 0)
return;
if (_messageInfoLogic == null)
return;
var List = await ReceiveMailImpl();
_logger.LogDebug("CheckMailAsync: New mails: {Count}", List.Count);
foreach (var Mail in List)
{
_messageInfoLogic.Create(Mail);
}
}
protected abstract Task SendMailImpl(MailSendInfoBindingModel Info);
protected abstract Task<List<MessageInfoBindingModel>> ReceiveMailImpl();
}
}

View File

@ -0,0 +1,87 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using MailKit.Net.Pop3;
using MailKit.Security;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Net.Mail;
using System.Text;
namespace BarBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
public MailKitWorker(ILogger<MailKitWorker> Logger, IMessageInfoLogic MessageInfoLogic)
: base(Logger, MessageInfoLogic) { }
protected override async Task SendMailImpl(MailSendInfoBindingModel Info)
{
using var MailMessage = new MailMessage();
using var SmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort);
try
{
MailMessage.From = new MailAddress(_mailLogin);
MailMessage.To.Add(new MailAddress(Info.MailAddress));
MailMessage.Subject = Info.Subject;
MailMessage.Body = Info.Text;
MailMessage.SubjectEncoding = Encoding.UTF8;
MailMessage.BodyEncoding = Encoding.UTF8;
SmtpClient.UseDefaultCredentials = false;
SmtpClient.EnableSsl = true;
SmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword);
await Task.Run(() => SmtpClient.Send(MailMessage));
}
catch (Exception)
{
throw;
}
}
protected override async Task<List<MessageInfoBindingModel>> ReceiveMailImpl()
{
var Result = new List<MessageInfoBindingModel>();
using var Client = new Pop3Client();
await Task.Run(() =>
{
try
{
Client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect);
Client.Authenticate(_mailLogin, _mailPassword);
for (int i = 0; i < Client.Count; i++)
{
var Message = Client.GetMessage(i);
foreach (var Mail in Message.From.Mailboxes)
{
//if (Mail.Address.Contains("o.filippova"))
Result.Add(new MessageInfoBindingModel
{
DateDelivery = Message.Date.DateTime,
MessageId = Message.MessageId,
SenderName = Mail.Address,
Subject = Message.Subject,
Body = Message.TextBody
});
}
}
}
catch (AuthenticationException)
{ }
finally
{
Client.Disconnect(true);
}
});
return Result;
}
}
}

View File

@ -0,0 +1,90 @@
using BarBusinessLogic.OfficePackage.HelperEnums;
using BarBusinessLogic.OfficePackage.HelperModels;
namespace BarBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToExcel
{
public void CreateReport(ExcelInfo Info)
{
CreateExcel(Info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = Info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "C1"
});
uint RowIndex = 2;
foreach (var RepComp in Info.CocktailComponents)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = RowIndex,
Text = RepComp.CocktailName,
StyleInfo = ExcelStyleInfoType.Text
});
RowIndex++;
foreach (var (Component, Count) in RepComp.Components)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = RowIndex,
Text = Component,
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = RowIndex,
Text = Count.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
RowIndex++;
}
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = RowIndex,
Text = "Итого",
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = RowIndex,
Text = RepComp.TotalCount.ToString(),
StyleInfo = ExcelStyleInfoType.Text
});
RowIndex++;
}
SaveExcel(Info);
}
protected abstract void CreateExcel(ExcelInfo Info);
protected abstract void InsertCellInWorksheet(ExcelCellParameters ExcelParams);
protected abstract void MergeCells(ExcelMergeParameters ExcelParams);
protected abstract void SaveExcel(ExcelInfo Info);
}
}

View File

@ -0,0 +1,47 @@
using BarBusinessLogic.OfficePackage.HelperEnums;
using BarBusinessLogic.OfficePackage.HelperModels;
namespace BarBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdf
{
public void CreateDoc(PdfInfo Info)
{
CreatePdf(Info);
CreateParagraph(new PdfParagraph { Text = Info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateParagraph(new PdfParagraph { Text = $"с {Info.DateFrom.ToShortDateString()} по {Info.DateTo.ToShortDateString()}", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateTable(new List<string> { "2cm", "3cm", "3cm", "4cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Номер", "Дата заказа", "Коктейль", "Статус", "Сумма" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var order in Info.Orders)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { order.Id.ToString(), order.DateCreate.ToShortDateString(), order.CocktailName, order.Status.ToString(), order.Sum.ToString() },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph { Text = $"Итого: {Info.Orders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Rigth });
SavePdf(Info);
}
protected abstract void CreatePdf(PdfInfo Info);
protected abstract void CreateParagraph(PdfParagraph Paragraph);
protected abstract void CreateTable(List<string> Columns);
protected abstract void CreateRow(PdfRowParameters RowParameters);
protected abstract void SavePdf(PdfInfo Info);
}
}

View File

@ -0,0 +1,48 @@
using BarBusinessLogic.OfficePackage.HelperEnums;
using BarBusinessLogic.OfficePackage.HelperModels;
namespace BarBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToWord
{
public void CreateDoc(WordInfo Info)
{
CreateWord(Info);
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (Info.Title, new WordTextProperties { Bold = true, Size = "24", }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
foreach (var Cocktails in Info.Cocktails)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> {
(Cocktails.CocktailName, new WordTextProperties { Size = "24", Bold = true}),
("\t"+Cocktails.Price.ToString(), new WordTextProperties{Size = "24"})
},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
SaveWord(Info);
}
protected abstract void CreateWord(WordInfo Info);
protected abstract void CreateParagraph(WordParagraph Paragraph);
protected abstract void SaveWord(WordInfo Info);
}
}

View File

@ -0,0 +1,9 @@
namespace BarBusinessLogic.OfficePackage.HelperEnums
{
public enum ExcelStyleInfoType
{
Title,
Text,
TextWithBroder
}
}

View File

@ -0,0 +1,9 @@
namespace BarBusinessLogic.OfficePackage.HelperEnums
{
public enum PdfParagraphAlignmentType
{
Center,
Left,
Rigth
}
}

View File

@ -0,0 +1,8 @@
namespace BarBusinessLogic.OfficePackage.HelperEnums
{
public enum WordJustificationType
{
Center,
Both
}
}

View File

@ -0,0 +1,17 @@
using BarBusinessLogic.OfficePackage.HelperEnums;
namespace BarBusinessLogic.OfficePackage.HelperModels
{
public class ExcelCellParameters
{
public string ColumnName { get; set; } = string.Empty;
public uint RowIndex { get; set; }
public string Text { get; set; } = string.Empty;
public string CellReference => $"{ColumnName}{RowIndex}";
public ExcelStyleInfoType StyleInfo { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using BarContracts.ViewModels;
namespace BarBusinessLogic.OfficePackage.HelperModels
{
public class ExcelInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportCocktailComponentViewModel> CocktailComponents { get; set; } = new();
}
}

View File

@ -0,0 +1,11 @@
namespace BarBusinessLogic.OfficePackage.HelperModels
{
public class ExcelMergeParameters
{
public string CellFromName { get; set; } = string.Empty;
public string CellToName { get; set; } = string.Empty;
public string Merge => $"{CellFromName}:{CellToName}";
}
}

View File

@ -0,0 +1,17 @@
using BarContracts.ViewModels;
namespace BarBusinessLogic.OfficePackage.HelperModels
{
public class PdfInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportOrdersViewModel> Orders { get; set; } = new();
}
}

View File

@ -0,0 +1,13 @@
using BarBusinessLogic.OfficePackage.HelperEnums;
namespace BarBusinessLogic.OfficePackage.HelperModels
{
public class PdfParagraph
{
public string Text { get; set; } = string.Empty;
public string Style { get; set; } = string.Empty;
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using BarBusinessLogic.OfficePackage.HelperEnums;
namespace BarBusinessLogic.OfficePackage.HelperModels
{
public class PdfRowParameters
{
public List<string> Texts { get; set; } = new();
public string Style { get; set; } = string.Empty;
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using BarContracts.ViewModels;
namespace BarBusinessLogic.OfficePackage.HelperModels
{
public class WordInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<CocktailViewModel> Cocktails { get; set; } = new();
}
}

View File

@ -0,0 +1,9 @@
namespace BarBusinessLogic.OfficePackage.HelperModels
{
public class WordParagraph
{
public List<(string, WordTextProperties)> Texts { get; set; } = new();
public WordTextProperties? TextProperties { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using BarBusinessLogic.OfficePackage.HelperEnums;
namespace BarBusinessLogic.OfficePackage.HelperModels
{
public class WordTextProperties
{
public string Size { get; set; } = string.Empty;
public bool Bold { get; set; }
public WordJustificationType JustificationType { get; set; }
}
}

View File

@ -0,0 +1,281 @@
using BarBusinessLogic.OfficePackage.HelperEnums;
using BarBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace BarBusinessLogic.OfficePackage.Implements
{
public class SaveToExcel : AbstractSaveToExcel
{
private SpreadsheetDocument? _spreadsheetDocument;
private SharedStringTablePart? _shareStringPart;
private Worksheet? _worksheet;
private static void CreateStyles(WorkbookPart WorkbookPart)
{
var sp = WorkbookPart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
var Fonts = new Fonts() { Count = 2U, KnownFonts = true };
var FontUsual = new Font();
FontUsual.Append(new FontSize() { Val = 12D });
FontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
FontUsual.Append(new FontName() { Val = "Times New Roman" });
FontUsual.Append(new FontFamilyNumbering() { Val = 2 });
FontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor });
var FontTitle = new Font();
FontTitle.Append(new Bold());
FontTitle.Append(new FontSize() { Val = 14D });
FontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
FontTitle.Append(new FontName() { Val = "Times New Roman" });
FontTitle.Append(new FontFamilyNumbering() { Val = 2 });
FontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
Fonts.Append(FontUsual);
Fonts.Append(FontTitle);
var Fills = new Fills() { Count = 2U };
var Fill1 = new Fill();
Fill1.Append(new PatternFill() { PatternType = PatternValues.None });
var Fill2 = new Fill();
Fill2.Append(new PatternFill() { PatternType = PatternValues.Gray125 });
Fills.Append(Fill1);
Fills.Append(Fill2);
var Borders = new Borders() { Count = 2U };
var BorderNoBorder = new Border();
BorderNoBorder.Append(new LeftBorder());
BorderNoBorder.Append(new RightBorder());
BorderNoBorder.Append(new TopBorder());
BorderNoBorder.Append(new BottomBorder());
BorderNoBorder.Append(new DiagonalBorder());
var BorderThin = new Border();
var LeftBorder = new LeftBorder() { Style = BorderStyleValues.Thin };
LeftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var RightBorder = new RightBorder() { Style = BorderStyleValues.Thin };
RightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var TopBorder = new TopBorder() { Style = BorderStyleValues.Thin };
TopBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin };
BottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
BorderThin.Append(LeftBorder);
BorderThin.Append(RightBorder);
BorderThin.Append(TopBorder);
BorderThin.Append(BottomBorder);
BorderThin.Append(new DiagonalBorder());
Borders.Append(BorderNoBorder);
Borders.Append(BorderThin);
var CellStyleFormats = new CellStyleFormats() { Count = 1U };
var CellFormatStyle = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U };
CellStyleFormats.Append(CellFormatStyle);
var CellFormats = new CellFormats() { Count = 3U };
var CellFormatFont = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U, FormatId = 0U, ApplyFont = true };
var CellFormatFontAndBorder = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 1U, FormatId = 0U, ApplyFont = true, ApplyBorder = true };
var CellFormatTitle = new CellFormat() { NumberFormatId = 0U, FontId = 1U, FillId = 0U, BorderId = 0U, FormatId = 0U, Alignment = new Alignment() { Vertical = VerticalAlignmentValues.Center, WrapText = true, Horizontal = HorizontalAlignmentValues.Center }, ApplyFont = true };
CellFormats.Append(CellFormatFont);
CellFormats.Append(CellFormatFontAndBorder);
CellFormats.Append(CellFormatTitle);
var CellStyles = new CellStyles() { Count = 1U };
CellStyles.Append(new CellStyle() { Name = "Normal", FormatId = 0U, BuiltinId = 0U });
var DifferentialFormats = new DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats() { Count = 0U };
var TableStyles = new TableStyles() { Count = 0U, DefaultTableStyle = "TableStyleMedium2", DefaultPivotStyle = "PivotStyleLight16" };
var StylesheetExtensionList = new StylesheetExtensionList();
var StylesheetExtension1 = new StylesheetExtension() { Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" };
StylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
StylesheetExtension1.Append(new SlicerStyles() { DefaultSlicerStyle = "SlicerStyleLight1" });
var StylesheetExtension2 = new StylesheetExtension() { Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}" };
StylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
StylesheetExtension2.Append(new TimelineStyles() { DefaultTimelineStyle = "TimeSlicerStyleLight1" });
StylesheetExtensionList.Append(StylesheetExtension1);
StylesheetExtensionList.Append(StylesheetExtension2);
sp.Stylesheet.Append(Fonts);
sp.Stylesheet.Append(Fills);
sp.Stylesheet.Append(Borders);
sp.Stylesheet.Append(CellStyleFormats);
sp.Stylesheet.Append(CellFormats);
sp.Stylesheet.Append(CellStyles);
sp.Stylesheet.Append(DifferentialFormats);
sp.Stylesheet.Append(TableStyles);
sp.Stylesheet.Append(StylesheetExtensionList);
}
private static uint GetStyleValue(ExcelStyleInfoType StyleInfo)
{
return StyleInfo switch
{
ExcelStyleInfoType.Title => 2U,
ExcelStyleInfoType.TextWithBroder => 1U,
ExcelStyleInfoType.Text => 0U,
_ => 0U,
};
}
protected override void CreateExcel(ExcelInfo Info)
{
_spreadsheetDocument = SpreadsheetDocument.Create(Info.FileName, SpreadsheetDocumentType.Workbook);
var WorkbookPart = _spreadsheetDocument.AddWorkbookPart();
WorkbookPart.Workbook = new Workbook();
CreateStyles(WorkbookPart);
_shareStringPart = _spreadsheetDocument.WorkbookPart!.GetPartsOfType<SharedStringTablePart>().Any()
? _spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First()
: _spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
// Создаем SharedStringTable, если его нет
if (_shareStringPart.SharedStringTable == null)
{
_shareStringPart.SharedStringTable = new SharedStringTable();
}
// Создаем лист в книгу
var WorksheetPart = WorkbookPart.AddNewPart<WorksheetPart>();
WorksheetPart.Worksheet = new Worksheet(new SheetData());
// Добавляем лист в книгу
var Sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
var Sheet = new Sheet()
{
Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(WorksheetPart),
SheetId = 1,
Name = "Лист"
};
Sheets.Append(Sheet);
_worksheet = WorksheetPart.Worksheet;
}
protected override void InsertCellInWorksheet(ExcelCellParameters ExcelParams)
{
if (_worksheet == null || _shareStringPart == null)
{
return;
}
var SheetData = _worksheet.GetFirstChild<SheetData>();
if (SheetData == null)
{
return;
}
// Ищем строку, либо добавляем ее
Row row;
if (SheetData.Elements<Row>().Where(r => r.RowIndex! == ExcelParams.RowIndex).Any())
{
row = SheetData.Elements<Row>().Where(r => r.RowIndex! == ExcelParams.RowIndex).First();
}
else
{
row = new Row() { RowIndex = ExcelParams.RowIndex };
SheetData.Append(row);
}
// Ищем нужную ячейку
Cell cell;
if (row.Elements<Cell>().Where(c => c.CellReference!.Value == ExcelParams.CellReference).Any())
{
cell = row.Elements<Cell>().Where(c => c.CellReference!.Value == ExcelParams.CellReference).First();
}
else
{
// Все ячейки должны быть последовательно друг за другом расположены
// нужно определить, после какой вставлять
Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference!.Value, ExcelParams.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var NewCell = new Cell() { CellReference = ExcelParams.CellReference };
row.InsertBefore(NewCell, refCell);
cell = NewCell;
}
// вставляем новый текст
_shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(ExcelParams.Text)));
_shareStringPart.SharedStringTable.Save();
cell.CellValue = new CellValue((_shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count() - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = GetStyleValue(ExcelParams.StyleInfo);
}
protected override void MergeCells(ExcelMergeParameters ExcelParams)
{
if (_worksheet == null)
{
return;
}
MergeCells MergeCells;
if (_worksheet.Elements<MergeCells>().Any())
{
MergeCells = _worksheet.Elements<MergeCells>().First();
}
else
{
MergeCells = new MergeCells();
if (_worksheet.Elements<CustomSheetView>().Any())
{
_worksheet.InsertAfter(MergeCells, _worksheet.Elements<CustomSheetView>().First());
}
else
{
_worksheet.InsertAfter(MergeCells, _worksheet.Elements<SheetData>().First());
}
}
var MergeCell = new MergeCell()
{
Reference = new StringValue(ExcelParams.Merge)
};
MergeCells.Append(MergeCell);
}
protected override void SaveExcel(ExcelInfo Info)
{
if (_spreadsheetDocument == null)
return;
_spreadsheetDocument.WorkbookPart!.Workbook.Save();
_spreadsheetDocument.Close();
}
}
}

View File

@ -0,0 +1,108 @@
using BarBusinessLogic.OfficePackage.HelperEnums;
using BarBusinessLogic.OfficePackage.HelperModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
namespace BarBusinessLogic.OfficePackage.Implements
{
public class SaveToPdf : AbstractSaveToPdf
{
private Document? _document;
private Section? _section;
private Table? _table;
private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType Type)
{
return Type switch
{
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
PdfParagraphAlignmentType.Left => ParagraphAlignment.Left,
PdfParagraphAlignmentType.Rigth => ParagraphAlignment.Right,
_ => ParagraphAlignment.Justify,
};
}
private static void DefineStyles(Document Document)
{
var Style = Document.Styles["Normal"];
Style.Font.Name = "Times New Roman";
Style.Font.Size = 14;
Style = Document.Styles.AddStyle("NormalTitle", "Normal");
Style.Font.Bold = true;
}
protected override void CreatePdf(PdfInfo Info)
{
_document = new Document();
DefineStyles(_document);
_section = _document.AddSection();
}
protected override void CreateParagraph(PdfParagraph PdfParagraph)
{
if (_section == null)
return;
var Paragraph = _section.AddParagraph(PdfParagraph.Text);
Paragraph.Format.SpaceAfter = "1cm";
Paragraph.Format.Alignment = GetParagraphAlignment(PdfParagraph.ParagraphAlignment);
Paragraph.Style = PdfParagraph.Style;
}
protected override void CreateTable(List<string> Columns)
{
if (_document == null)
return;
_table = _document.LastSection.AddTable();
foreach (var Elem in Columns)
{
_table.AddColumn(Elem);
}
}
protected override void CreateRow(PdfRowParameters RowParameters)
{
if (_table == null)
return;
var Row = _table.AddRow();
for (int i = 0; i < RowParameters.Texts.Count; ++i)
{
Row.Cells[i].AddParagraph(RowParameters.Texts[i]);
if (!string.IsNullOrEmpty(RowParameters.Style))
{
Row.Cells[i].Style = RowParameters.Style;
}
Unit borderWidth = 0.5;
Row.Cells[i].Borders.Left.Width = borderWidth;
Row.Cells[i].Borders.Right.Width = borderWidth;
Row.Cells[i].Borders.Top.Width = borderWidth;
Row.Cells[i].Borders.Bottom.Width = borderWidth;
Row.Cells[i].Format.Alignment = GetParagraphAlignment(RowParameters.ParagraphAlignment);
Row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
protected override void SavePdf(PdfInfo Info)
{
var Renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
Renderer.RenderDocument();
Renderer.PdfDocument.Save(Info.FileName);
}
}
}

View File

@ -0,0 +1,118 @@
using BarBusinessLogic.OfficePackage.HelperEnums;
using BarBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace BarBusinessLogic.OfficePackage.Implements
{
public class SaveToWord : AbstractSaveToWord
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
private static JustificationValues GetJustificationValues(WordJustificationType Type)
{
return Type switch
{
WordJustificationType.Both => JustificationValues.Both,
WordJustificationType.Center => JustificationValues.Center,
_ => JustificationValues.Left,
};
}
private static SectionProperties CreateSectionProperties()
{
var Properties = new SectionProperties();
var PageSize = new PageSize
{
Orient = PageOrientationValues.Portrait
};
Properties.AppendChild(PageSize);
return Properties;
}
private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? ParagraphProperties)
{
if (ParagraphProperties == null)
return null;
var Properties = new ParagraphProperties();
Properties.AppendChild(new Justification()
{
Val = GetJustificationValues(ParagraphProperties.JustificationType)
});
Properties.AppendChild(new SpacingBetweenLines
{
LineRule = LineSpacingRuleValues.Auto
});
Properties.AppendChild(new Indentation());
var ParagraphMarkRunProperties = new ParagraphMarkRunProperties();
if (!string.IsNullOrEmpty(ParagraphProperties.Size))
{
ParagraphMarkRunProperties.AppendChild(new FontSize { Val = ParagraphProperties.Size });
}
Properties.AppendChild(ParagraphMarkRunProperties);
return Properties;
}
protected override void CreateWord(WordInfo Info)
{
_wordDocument = WordprocessingDocument.Create(Info.FileName, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
_docBody = mainPart.Document.AppendChild(new Body());
}
protected override void CreateParagraph(WordParagraph Paragraph)
{
if (_docBody == null || Paragraph == null)
{
return;
}
var DocParagraph = new Paragraph();
DocParagraph.AppendChild(CreateParagraphProperties(Paragraph.TextProperties));
foreach (var Run in Paragraph.Texts)
{
var DocRun = new Run();
var Properties = new RunProperties();
Properties.AppendChild(new FontSize { Val = Run.Item2.Size });
if (Run.Item2.Bold)
{
Properties.AppendChild(new Bold());
}
DocRun.AppendChild(Properties);
DocRun.AppendChild(new Text { Text = Run.Item1, Space = SpaceProcessingModeValues.Preserve });
DocParagraph.AppendChild(DocRun);
}
_docBody.AppendChild(DocParagraph);
}
protected override void SaveWord(WordInfo Info)
{
if (_docBody == null || _wordDocument == null)
{
return;
}
_docBody.AppendChild(CreateSectionProperties());
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Close();
}
}
}

View File

@ -0,0 +1,49 @@
using BarContracts.ViewModels;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace BarClientApp
{
public static class ApiClient
{
private static readonly HttpClient _client = new();
public static ClientViewModel? Client { get; set; } = null;
public static void Connect(IConfiguration Configuration)
{
_client.BaseAddress = new Uri(Configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string RequestUrl)
{
var Response = _client.GetAsync(RequestUrl);
var Result = Response.Result.Content.ReadAsStringAsync().Result;
if (Response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(Result);
}
else
{
throw new Exception(Result);
}
}
public static void PostRequest<T>(string RequestUrl, T Model)
{
var Json = JsonConvert.SerializeObject(Model);
var Data = new StringContent(Json, Encoding.UTF8, "application/json");
var Response = _client.PostAsync(RequestUrl, Data);
var Result = Response.Result.Content.ReadAsStringAsync().Result;
if (!Response.Result.IsSuccessStatusCode)
{
throw new Exception(Result);
}
}
}
}

View File

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BarBusinessLogic\BarBusinessLogic\BarBusinessLogic.csproj" />
<ProjectReference Include="..\BarContracts\BarContracts\BarContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,171 @@
using BarClientApp.Models;
using BarContracts.BindingModels;
using BarContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
namespace BarClientApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> Logger)
{
_logger = Logger;
}
public IActionResult Index()
{
if (ApiClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(ApiClient.GetRequest<List<OrderViewModel>>($"api/main/getorders?clientId={ApiClient.Client.Id}"));
}
[HttpGet]
public IActionResult Privacy()
{
if (ApiClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(ApiClient.Client);
}
[HttpPost]
public void Privacy(string login, string password, string fio)
{
if (ApiClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{
throw new Exception("Введите логин, пароль и ФИО");
}
ApiClient.PostRequest("api/client/updatedata", new ClientBindingModel
{
Id = ApiClient.Client.Id,
ClientFIO = fio,
Email = login,
Password = password
});
ApiClient.Client.ClientFIO = fio;
ApiClient.Client.Email = login;
ApiClient.Client.Password = password;
Response.Redirect("Index");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
});
}
[HttpGet]
public IActionResult Enter()
{
return View();
}
[HttpPost]
public void Enter(string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин и пароль");
}
ApiClient.Client = ApiClient.GetRequest<ClientViewModel>($"api/client/login?login={login}&password={password}");
if (ApiClient.Client == null)
{
throw new Exception("Неверный логин/пароль");
}
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public void Register(string login, string password, string fio)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{
throw new Exception("Введите логин, пароль и ФИО");
}
ApiClient.PostRequest("api/client/register", new ClientBindingModel
{
ClientFIO = fio,
Email = login,
Password = password
});
Response.Redirect("Enter");
return;
}
[HttpGet]
public IActionResult Create()
{
ViewBag.Cocktails = ApiClient.GetRequest<List<CocktailViewModel>>("api/main/getcocktaillist");
return View();
}
[HttpPost]
public void Create(int cocktail, int count)
{
if (ApiClient.Client == null)
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
if (count <= 0)
throw new Exception("Количество и сумма должны быть больше 0");
ApiClient.PostRequest("api/main/createorder", new OrderBindingModel
{
ClientId = ApiClient.Client.Id,
CocktailId = cocktail,
Count = count,
Sum = Calc(count, cocktail)
});
Response.Redirect("Index");
}
[HttpPost]
public double Calc(int count, int cocktail)
{
CocktailViewModel? Cocktail = ApiClient.GetRequest<CocktailViewModel>($"api/main/getcocktail?cocktailId={cocktail}");
return count * (Cocktail?.Price ?? 1);
}
[HttpGet]
public IActionResult Mails()
{
if (ApiClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(ApiClient.GetRequest<List<MessageInfoViewModel>>($"api/client/getmessages?clientId={ApiClient.Client.Id}"));
}
}
}

View File

@ -0,0 +1,9 @@
namespace BarClientApp.Models
{
public class ErrorViewModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}

View File

@ -0,0 +1,24 @@
using BarClientApp;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
ApiClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
app.Run();

View File

@ -0,0 +1,28 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:32797",
"sslPort": 44371
}
},
"profiles": {
"BarClientApp": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7145;http://localhost:5218",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,56 @@
@{
ViewData["Title"] = "Create";
}
<div class="text-center">
<h2 class="display-4">Создание заказа</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Коктейль:</div>
<div class="col-8">
<select id="cocktail" name="cocktail" class="form-control" asp-items="@(new SelectList(@ViewBag.Cocktails,"Id", "CocktailName"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Количество:</div>
<div class="col-8">
<input type="text" name="count" id="count" />
</div>
</div>
<div class="row">
<div class="col-4">Сумма:</div>
<div class="col-8">
<input type="text" id="sum" name="sum" readonly />
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Создать" class="btn btn-primary" />
</div>
</div>
</form>
<script>
$('#cocktail').on('change', function () {
check();
});
$('#count').on('change', function () {
check();
});
function check() {
var count = $('#count').val();
var cocktail = $('#cocktail').val();
if (count && cocktail) {
$.ajax({
method: "POST",
url: "/Home/Calc",
data: { count: count, cocktail: cocktail },
success: function (result) {
$("#sum").val(result);
}
});
};
}
</script>

View File

@ -0,0 +1,20 @@
@{
ViewData["Title"] = "Enter";
}
<div class="text-center">
<h2 class="display-4">Вход в приложение</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Вход" class="btn btnprimary" /></div>
</div>
</form>

View File

@ -0,0 +1,69 @@
@using BarContracts.ViewModels
@model List<OrderViewModel>
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Заказы</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<p>
<a asp-action="Create">Создать заказ</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Номер
</th>
<th>
Коктейль
</th>
<th>
Дата создания
</th>
<th>
Количество
</th>
<th>
Сумма
</th>
<th>
Статус
</th>
</tr>
</thead>
<tbody>
@foreach (var Item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => Item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => Item.CocktailName)
</td>
<td>
@Html.DisplayFor(modelItem => Item.DateCreate)
</td>
<td>
@Html.DisplayFor(modelItem => Item.Count)
</td>
<td>
@Html.DisplayFor(modelItem => Item.Sum)
</td>
<td>
@Html.DisplayFor(modelItem => Item.Status)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,51 @@
@using BarContracts.ViewModels
@model List<MessageInfoViewModel>
@{
ViewData["Title"] = "Mails";
}
<div class="text-center">
<h1 class="display-4">Заказы</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<table class="table">
<thead>
<tr>
<th>
Дата письма
</th>
<th>
Заголовок
</th>
<th>
Текст
</th>
</tr>
</thead>
<tbody>
@foreach (var Item in Model)
{
<tr>
<td>
@Html.DisplayFor(ModelItem => Item.DateDelivery)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.Subject)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.Body)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,34 @@
@using BarContracts.ViewModels
@model ClientViewModel
@{
ViewData["Title"] = "Privacy Policy";
}
<div class="text-center">
<h2 class="display-4">Личные данные</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8">
<input type="text" name="login" value="@Model.Email"/>
</div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8">
<input type="password" name="password" value="@Model.Password"/>
</div>
</div>
<div class="row">
<div class="col-4">ФИО:</div>
<div class="col-8">
<input type="text" name="fio" value="@Model.ClientFIO"/>
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Сохранить" class="btn btn-primary" />
</div>
</div>
</form>

View File

@ -0,0 +1,28 @@
@{
ViewData["Title"] = "Register";
}
<div class="text-center">
<h2 class="display-4">Регистрация</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div>
</div>
<div class="row">
<div class="col-4">ФИО:</div>
<div class="col-8"><input type="text" name="fio" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Регистрация"
class="btn btn-primary" />
</div>
</div>
</form>

View File

@ -0,0 +1,25 @@
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>

Some files were not shown because too many files have changed in this diff Show More