лаба 1 усложненная

This commit is contained in:
a.puchkina 2024-03-26 17:42:09 +04:00
parent a20b7ca0f2
commit 1e5de3e27b
15 changed files with 819 additions and 172 deletions

View File

@ -40,9 +40,10 @@
// //
// buttonCancel // buttonCancel
// //
buttonCancel.Location = new Point(338, 156); buttonCancel.Location = new Point(296, 117);
buttonCancel.Margin = new Padding(3, 2, 3, 2);
buttonCancel.Name = "buttonCancel"; buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29); buttonCancel.Size = new Size(82, 22);
buttonCancel.TabIndex = 15; buttonCancel.TabIndex = 15;
buttonCancel.Text = "Отмена"; buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true; buttonCancel.UseVisualStyleBackColor = true;
@ -50,9 +51,10 @@
// //
// buttonSave // buttonSave
// //
buttonSave.Location = new Point(210, 156); buttonSave.Location = new Point(184, 117);
buttonSave.Margin = new Padding(3, 2, 3, 2);
buttonSave.Name = "buttonSave"; buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29); buttonSave.Size = new Size(82, 22);
buttonSave.TabIndex = 14; buttonSave.TabIndex = 14;
buttonSave.Text = "Сохранить"; buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true; buttonSave.UseVisualStyleBackColor = true;
@ -60,59 +62,62 @@
// //
// textBoxCount // textBoxCount
// //
textBoxCount.Location = new Point(154, 100); textBoxCount.Location = new Point(135, 75);
textBoxCount.Margin = new Padding(3, 2, 3, 2);
textBoxCount.Name = "textBoxCount"; textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(278, 27); textBoxCount.Size = new Size(244, 23);
textBoxCount.TabIndex = 13; textBoxCount.TabIndex = 13;
// //
// comboBoxShop // comboBoxShop
// //
comboBoxShop.FormattingEnabled = true; comboBoxShop.FormattingEnabled = true;
comboBoxShop.Location = new Point(154, 13); comboBoxShop.Location = new Point(135, 10);
comboBoxShop.Margin = new Padding(3, 2, 3, 2);
comboBoxShop.Name = "comboBoxShop"; comboBoxShop.Name = "comboBoxShop";
comboBoxShop.Size = new Size(278, 28); comboBoxShop.Size = new Size(244, 23);
comboBoxShop.TabIndex = 11; comboBoxShop.TabIndex = 11;
// //
// label3 // label3
// //
label3.AutoSize = true; label3.AutoSize = true;
label3.Location = new Point(55, 107); label3.Location = new Point(48, 80);
label3.Name = "label3"; label3.Name = "label3";
label3.Size = new Size(93, 20); label3.Size = new Size(75, 15);
label3.TabIndex = 10; label3.TabIndex = 10;
label3.Text = "Количество:"; label3.Text = "Количество:";
// //
// label2 // label2
// //
label2.AutoSize = true; label2.AutoSize = true;
label2.Location = new Point(77, 64); label2.Location = new Point(67, 48);
label2.Name = "label2"; label2.Name = "label2";
label2.Size = new Size(71, 20); label2.Size = new Size(56, 15);
label2.TabIndex = 9; label2.TabIndex = 9;
label2.Text = "Изделие:"; label2.Text = "Изделие:";
// //
// label1 // label1
// //
label1.AutoSize = true; label1.AutoSize = true;
label1.Location = new Point(76, 21); label1.Location = new Point(66, 16);
label1.Name = "label1"; label1.Name = "label1";
label1.Size = new Size(72, 20); label1.Size = new Size(57, 15);
label1.TabIndex = 8; label1.TabIndex = 8;
label1.Text = "Магазин:"; label1.Text = "Магазин:";
// //
// comboBoxTravel // comboBoxTravel
// //
comboBoxTravel.FormattingEnabled = true; comboBoxTravel.FormattingEnabled = true;
comboBoxTravel.Location = new Point(154, 56); comboBoxTravel.Location = new Point(135, 42);
comboBoxTravel.Margin = new Padding(3, 2, 3, 2);
comboBoxTravel.Name = "comboBoxTravel"; comboBoxTravel.Name = "comboBoxTravel";
comboBoxTravel.Size = new Size(278, 28); comboBoxTravel.Size = new Size(244, 23);
comboBoxTravel.TabIndex = 16; comboBoxTravel.TabIndex = 16;
// //
// FormCreateDelivery // FormCreateDelivery
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(490, 203); ClientSize = new Size(429, 152);
Controls.Add(comboBoxTravel); Controls.Add(comboBoxTravel);
Controls.Add(buttonCancel); Controls.Add(buttonCancel);
Controls.Add(buttonSave); Controls.Add(buttonSave);
@ -121,8 +126,10 @@
Controls.Add(label3); Controls.Add(label3);
Controls.Add(label2); Controls.Add(label2);
Controls.Add(label1); Controls.Add(label1);
Margin = new Padding(3, 2, 3, 2);
Name = "FormCreateDelivery"; Name = "FormCreateDelivery";
Text = "FormCreateDelivery"; Text = "FormCreateDelivery";
Load += FormCreateDelivery_Load;
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();
} }

View File

@ -28,12 +28,159 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.components = new System.ComponentModel.Container(); labelName = new Label();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; labelAddress = new Label();
this.ClientSize = new System.Drawing.Size(800, 450); labelDate = new Label();
this.Text = "FormShop"; textBoxName = new TextBox();
textBoxAddress = new TextBox();
dateOpenTimePicker = new DateTimePicker();
dataGridView = new DataGridView();
id = new DataGridViewTextBoxColumn();
TravelName = new DataGridViewTextBoxColumn();
Count = new DataGridViewTextBoxColumn();
buttonSave = new Button();
buttonCancel = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(12, 9);
labelName.Name = "labelName";
labelName.Size = new Size(62, 15);
labelName.TabIndex = 0;
labelName.Text = "Название:";
//
// labelAddress
//
labelAddress.AutoSize = true;
labelAddress.Location = new Point(12, 45);
labelAddress.Name = "labelAddress";
labelAddress.Size = new Size(43, 15);
labelAddress.TabIndex = 1;
labelAddress.Text = "Адрес:";
//
// labelDate
//
labelDate.AutoSize = true;
labelDate.Location = new Point(12, 78);
labelDate.Name = "labelDate";
labelDate.Size = new Size(90, 15);
labelDate.TabIndex = 2;
labelDate.Text = "Дата открытия:";
//
// textBoxName
//
textBoxName.Location = new Point(112, 6);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(277, 23);
textBoxName.TabIndex = 3;
//
// textBoxAddress
//
textBoxAddress.Location = new Point(112, 37);
textBoxAddress.Name = "textBoxAddress";
textBoxAddress.Size = new Size(277, 23);
textBoxAddress.TabIndex = 4;
//
// dateOpenTimePicker
//
dateOpenTimePicker.Location = new Point(112, 72);
dateOpenTimePicker.Name = "dateOpenTimePicker";
dateOpenTimePicker.Size = new Size(277, 23);
dateOpenTimePicker.TabIndex = 5;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { id, TravelName, Count });
dataGridView.Location = new Point(12, 112);
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
dataGridView.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders;
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(534, 261);
dataGridView.TabIndex = 6;
//
// id
//
id.HeaderText = "id";
id.Name = "id";
id.ReadOnly = true;
id.Visible = false;
//
// TravelName
//
TravelName.HeaderText = "Путевка";
TravelName.Name = "TravelName";
TravelName.ReadOnly = true;
//
// Count
//
Count.HeaderText = "Количество";
Count.Name = "Count";
Count.ReadOnly = true;
//
// buttonSave
//
buttonSave.Location = new Point(322, 379);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(109, 32);
buttonSave.TabIndex = 7;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(437, 379);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(109, 32);
buttonCancel.TabIndex = 8;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// FormShop
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(558, 423);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(dataGridView);
Controls.Add(dateOpenTimePicker);
Controls.Add(textBoxAddress);
Controls.Add(textBoxName);
Controls.Add(labelDate);
Controls.Add(labelAddress);
Controls.Add(labelName);
Name = "FormShop";
Text = "Магазин";
Load += FormShop_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
private Label labelName;
private Label labelAddress;
private Label labelDate;
private TextBox textBoxName;
private TextBox textBoxAddress;
private DateTimePicker dateOpenTimePicker;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn id;
private DataGridViewTextBoxColumn TravelName;
private DataGridViewTextBoxColumn Count;
private Button buttonSave;
private Button buttonCancel;
} }
} }

View File

@ -7,14 +7,120 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.BusinessLogicContracts;
using TravelCompanyDataModels.Models;
using TravelCompanyContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace TravelCompanyView namespace TravelCompanyView
{ {
public partial class FormShop : Form public partial class FormShop : Form
{ {
public FormShop() private readonly ILogger _logger;
private readonly IShopLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
private Dictionary<int, (ITravelModel, int)> _ShopTravels;
private DateTime? _openingDate = null;
public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger;
_logic = logic;
_ShopTravels = new Dictionary<int, (ITravelModel, int)>();
}
private void FormShop_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка магазина");
try
{
var view = _logic.ReadElement(new ShopSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.ShopName;
textBoxAddress.Text = view.Address;
dateOpenTimePicker.Value = view.OpeningDate;
_ShopTravels = view.ShopTravels ?? new Dictionary<int, (ITravelModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка изделий в магазине");
try
{
if (_ShopTravels != null)
{
dataGridView.Rows.Clear();
foreach (var sr in _ShopTravels)
{
dataGridView.Rows.Add(new object[] { sr.Key, sr.Value.Item1.TravelName, sr.Value.Item2 });
}
}
}
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(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxAddress.Text))
{
MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение магазина");
try
{
var model = new ShopBindingModel
{
Id = _id ?? 0,
ShopName = textBoxName.Text,
Address = textBoxAddress.Text,
OpeningDate = dateOpenTimePicker.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 buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
} }
} }
} }

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<!-- <!--
Microsoft ResX Schema Microsoft ResX Schema
Version 2.0 Version 2.0
The primary goals of this format is to allow a simple XML format The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes various data types are done through the TypeConverter classes
associated with the data types. associated with the data types.
Example: Example:
... ado.net/XML headers & schema ... ... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader> <resheader name="version">2.0</resheader>
@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment> <comment>This is a comment</comment>
</data> </data>
There are any number of "resheader" rows that contain simple There are any number of "resheader" rows that contain simple
name/value pairs. name/value pairs.
Each data row contains a name, and value. The row also contains a Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture. text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the Classes that don't support this are serialized and stored with the
mimetype set. mimetype set.
The mimetype is used for serialized objects, and tells the The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly: extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below. read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64 mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64 mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64 mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter : using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
--> -->
@ -117,4 +117,22 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="id.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="TravelName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Count.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="id.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="TravelName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Count.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root> </root>

View File

@ -0,0 +1,129 @@
namespace TravelCompanyView
{
partial class FormShops
{
/// <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();
ToolsPanel = new Panel();
buttonRef = new Button();
buttonDel = new Button();
buttonUpd = new Button();
buttonAdd = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
ToolsPanel.SuspendLayout();
SuspendLayout();
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 12);
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(618, 383);
dataGridView.TabIndex = 0;
//
// ToolsPanel
//
ToolsPanel.Controls.Add(buttonRef);
ToolsPanel.Controls.Add(buttonDel);
ToolsPanel.Controls.Add(buttonUpd);
ToolsPanel.Controls.Add(buttonAdd);
ToolsPanel.Location = new Point(640, 12);
ToolsPanel.Name = "ToolsPanel";
ToolsPanel.Size = new Size(150, 387);
ToolsPanel.TabIndex = 1;
//
// buttonRef
//
buttonRef.Location = new Point(22, 226);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(102, 42);
buttonRef.TabIndex = 3;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += buttonRef_Click;
//
// buttonDel
//
buttonDel.Location = new Point(22, 159);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(102, 42);
buttonDel.TabIndex = 2;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += buttonDel_Click;
//
// buttonUpd
//
buttonUpd.Location = new Point(22, 92);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(102, 42);
buttonUpd.TabIndex = 1;
buttonUpd.Text = "Изменить";
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += buttonUpd_Click;
//
// buttonAdd
//
buttonAdd.Location = new Point(22, 28);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(102, 42);
buttonAdd.TabIndex = 0;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// FormShops
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 407);
Controls.Add(ToolsPanel);
Controls.Add(dataGridView);
Name = "FormShops";
Text = "Магазины";
Load += FormShops_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ToolsPanel.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Panel ToolsPanel;
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
}
}

View File

@ -0,0 +1,116 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TravelCompany;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.BusinessLogicContracts;
namespace TravelCompanyView
{
public partial class FormShops : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public FormShops(ILogger<FormShops> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormShops_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ShopTravels"].Visible = false;
dataGridView.Columns["ShopName"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка магазинов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазинов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void buttonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void buttonDel_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 ShopBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void buttonRef_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>

View File

@ -2,6 +2,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging; using NLog.Extensions.Logging;
using TravelCompanyBusinessLogic.BusinessLogic; using TravelCompanyBusinessLogic.BusinessLogic;
using TravelCompanyContracts.BusinessLogicContracts;
using TravelCompanyContracts.BusinessLogicsContracts; using TravelCompanyContracts.BusinessLogicsContracts;
using TravelCompanyContracts.StoragesContracts; using TravelCompanyContracts.StoragesContracts;
using TravelCompanyListImplement.Implements; using TravelCompanyListImplement.Implements;
@ -36,7 +37,7 @@ namespace TravelCompany
option.AddNLog("nlog.config"); option.AddNLog("nlog.config");
}); });
services.AddTransient<IComponentStorage, ComponentStorage>(); services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<ITravelStorage, OrderStorage>(); services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<ITravelStorage, TravelStorage>(); services.AddTransient<ITravelStorage, TravelStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>(); services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>(); services.AddTransient<IOrderLogic, OrderLogic>();
@ -48,6 +49,11 @@ namespace TravelCompany
services.AddTransient<FormTravel>(); services.AddTransient<FormTravel>();
services.AddTransient<FormTravelComponent>(); services.AddTransient<FormTravelComponent>();
services.AddTransient<FormTravels>(); services.AddTransient<FormTravels>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormCreateDelivery>();
} }
} }
} }

View File

@ -20,9 +20,9 @@ namespace TravelCompanyBusinessLogic.BusinessLogic
//менять статус на новый, если его текущий статус предшествует новому //менять статус на новый, если его текущий статус предшествует новому
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly ITravelStorage _orderStorage; private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, ITravelStorage orderStorage) public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
{ {
_logger = logger; _logger = logger;
_orderStorage = orderStorage; _orderStorage = orderStorage;

View File

@ -10,155 +10,152 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using static TravelCompanyBusinessLogic.BusinessLogic.ShopLogic; using TravelCompanyContracts.BusinessLogicContracts;
namespace TravelCompanyBusinessLogic.BusinessLogic namespace TravelCompanyBusinessLogic.BusinessLogic
{ {
public class ShopLogic : IShopLogic public class ShopLogic : IShopLogic
{ {
public class ShopLogic : IShopLogic private readonly ILogger _logger;
private readonly IShopStorage _shopStorage;
private readonly ITravelStorage _travelStorage;
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage, ITravelStorage travelStorage)
{ {
private readonly ILogger _logger; _logger = logger;
private readonly IShopStorage _shopStorage; _shopStorage = shopStorage;
private readonly ITravelStorage _travelStorage; _travelStorage = travelStorage;
}
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage, ITravelStorage travelStorage) public List<ShopViewModel>? ReadList(ShopSearchModel? model)
{
_logger.LogInformation("ReadList. ShopName:{ShopName}.Id:{ Id}", model?.ShopName, model?.Id);
var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model);
if (list == null)
{ {
_logger = logger; _logger.LogWarning("ReadList return null list");
_shopStorage = shopStorage; return null;
_travelStorage = travelStorage;
} }
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public List<ShopViewModel>? ReadList(ShopSearchModel? model) public ShopViewModel? ReadElement(ShopSearchModel model)
{
if (model == null)
{ {
_logger.LogInformation("ReadList. ShopName:{ShopName}.Id:{ Id}", model?.ShopName, model?.Id); throw new ArgumentNullException(nameof(model));
var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
} }
_logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id);
public TravelViewModel? ReadElement(ShopSearchModel model) var element = _shopStorage.GetElement(model);
if (element == null)
{ {
if (model == null) _logger.LogWarning("ReadElement element not found");
{ return null;
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id);
var element = _shopStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
} }
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(ShopBindingModel model) public bool Create(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Insert(model) == null)
{ {
CheckModel(model); _logger.LogWarning("Insert operation failed");
if (_shopStorage.Insert(model) == null) return false;
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
} }
return true;
}
public bool Update(ShopBindingModel model) public bool Update(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Update(model) == null)
{ {
CheckModel(model); _logger.LogWarning("Update operation failed");
if (_shopStorage.Update(model) == null) return false;
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
} }
return true;
}
public bool Delete(ShopBindingModel model) public bool Delete(ShopBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_shopStorage.Delete(model) == null)
{ {
CheckModel(model, false); _logger.LogWarning("Delete operation failed");
_logger.LogInformation("Delete. Id:{Id}", model.Id); return false;
if (_shopStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
} }
return true;
}
public bool MakeSupply(SupplyBindingModel model) public bool MakeDelivery(DeliveryBindingModel model)
{
if (model == null)
{ {
if (model == null) throw new ArgumentNullException(nameof(model));
}
if (model.Count <= 0)
{
throw new ArgumentException("Количество изделий должно быть больше 0");
}
var shop = _shopStorage.GetElement(new ShopSearchModel
{
Id = model.ShopId
});
if (shop == null)
{
throw new ArgumentException("Магазина не существует");
}
if (shop.ShopTravels.ContainsKey(model.TravelId))
{
var oldValue = shop.ShopTravels[model.TravelId];
oldValue.Item2 += model.Count;
shop.ShopTravels[model.TravelId] = oldValue;
}
else
{
var Travel = _travelStorage.GetElement(new TravelSearchModel
{ {
throw new ArgumentNullException(nameof(model)); Id = model.TravelId
}
if (model.Count <= 0)
{
throw new ArgumentException("Количество изделий должно быть больше 0");
}
var shop = _shopStorage.GetElement(new ShopSearchModel
{
Id = model.ShopId
}); });
if (shop == null) if (Travel == null)
{ {
throw new ArgumentException("Магазина не существует"); throw new ArgumentException($"Поставка: Товар с id:{model.TravelId} не найденн");
} }
if (shop.ShopPizzas.ContainsKey(model.PizzaId)) shop.ShopTravels.Add(model.TravelId, (Travel, model.Count));
{
var oldValue = shop.ShopPizzas[model.PizzaId];
oldValue.Item2 += model.Count;
shop.ShopPizzas[model.PizzaId] = oldValue;
}
else
{
var pizza = _pizzaStorage.GetElement(new PizzaSearchModel
{
Id = model.PizzaId
});
if (pizza == null)
{
throw new ArgumentException($"Поставка: Товар с id:{model.PizzaId} не найденн");
}
shop.ShopPizzas.Add(model.PizzaId, (pizza, model.Count));
}
return true;
} }
return true;
}
private void CheckModel(ShopBindingModel model, bool withParams = true) private void CheckModel(ShopBindingModel model, bool withParams = true)
{
if (model == null)
{ {
if (model == null) throw new ArgumentNullException(nameof(model));
{ }
throw new ArgumentNullException(nameof(model)); if (!withParams)
} {
if (!withParams) return;
{ }
return; if (string.IsNullOrEmpty(model.Address))
} {
if (string.IsNullOrEmpty(model.Adress)) throw new ArgumentException("Адрес магазина длжен быть заполнен", nameof(model.Address));
{ }
throw new ArgumentException("Адрес магазина длжен быть заполнен", nameof(model.Adress)); if (string.IsNullOrEmpty(model.ShopName))
} {
if (string.IsNullOrEmpty(model.ShopName)) throw new ArgumentException("Название магазина должно быть заполнено", nameof(model.ShopName));
{ }
throw new ArgumentException("Название магазина должно быть заполнено", nameof(model.ShopName)); _logger.LogInformation("Shop. ShopName:{ShopName}.Adres:{Adres}.OpeningDate:{OpeningDate}.Id:{ Id}", model.ShopName, model.Address, model.OpeningDate, model.Id);
} var element = _shopStorage.GetElement(new ShopSearchModel
_logger.LogInformation("Shop. ShopName:{ShopName}.Adres:{Adres}.OpeningDate:{OpeningDate}.Id:{ Id}", model.ShopName, model.Adress, model.OpeningDate, model.Id); {
var element = _shopStorage.GetElement(new ShopSearchModel ShopName = model.ShopName
{ });
ShopName = model.ShopName if (element != null && element.Id != model.Id)
}); {
if (element != null && element.Id != model.Id) throw new InvalidOperationException("Магазин с таким названием уже есть");
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
} }
} }
} }

View File

@ -12,7 +12,7 @@ using System.Threading.Tasks;
namespace TravelCompanyBusinessLogic.BusinessLogic namespace TravelCompanyBusinessLogic.BusinessLogic
{ {
public class TravelLogic : TravelCompanyContracts.BusinessLogicsContracts.ITravelLogic public class TravelLogic : ITravelLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly ITravelStorage _TravelStorage; private readonly ITravelStorage _TravelStorage;

View File

@ -17,6 +17,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\TravelCompanyContracts\TravelCompanyContracts.csproj" /> <ProjectReference Include="..\TravelCompanyContracts\TravelCompanyContracts.csproj" />
<ProjectReference Include="..\TravelCompanyDataModels\TravelCompanyDataModels.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -13,6 +13,6 @@ namespace TravelCompanyContracts.BindingModels
public string ShopName { get; set; } = string.Empty; public string ShopName { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty; public string Address { get; set; } = string.Empty;
public DateTime OpeningDate { get; set; } = DateTime.Now; public DateTime OpeningDate { get; set; } = DateTime.Now;
public Dictionary<int, (ITravelModel, int)> ShopPizzas { get; set; } = new(); public Dictionary<int, (ITravelModel, int)> ShopTravels { get; set; } = new();
} }
} }

View File

@ -9,7 +9,7 @@ using System.Threading.Tasks;
namespace TravelCompanyContracts.StoragesContracts namespace TravelCompanyContracts.StoragesContracts
{ {
public interface ITravelStorage public interface IOrderStorage
{ {
List<OrderViewModel> GetFullList(); List<OrderViewModel> GetFullList();
List<OrderViewModel> GetFilteredList(OrderSearchModel model); List<OrderViewModel> GetFilteredList(OrderSearchModel model);

View File

@ -11,7 +11,7 @@ using System.Threading.Tasks;
namespace TravelCompanyListImplement.Implements namespace TravelCompanyListImplement.Implements
{ {
public class OrderStorage : ITravelStorage public class OrderStorage : IOrderStorage
{ {
private readonly DataListSingleton _source; private readonly DataListSingleton _source;