From c9ad7127f94c3c518a228139e20fa2c43ed8dd27 Mon Sep 17 00:00:00 2001 From: Roman-Klemendeev <147613551+Roman-Klemendeev@users.noreply.github.com> Date: Sun, 26 May 2024 22:15:39 +0400 Subject: [PATCH] =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D0=B0=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Conflicts: # ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/ListGenericObjects.cs # ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/StorageCollection.cs # ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.Designer.cs # ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.cs --- .../AbstractCompany.cs | 13 +- .../CollectionGenericObjects/CarPark.cs | 10 +- .../ListGenericObjects.cs | 28 +- .../MassiveGenericObjects.cs | 24 +- .../StorageCollection.cs | 34 ++- .../Exceptions/CollectionOverflowException.cs | 17 ++ .../Exceptions/ObjectNotFoundException.cs | 16 ++ .../PositionOutOfCollectionException.cs | 16 ++ .../FormTankerCollection.Designer.cs | 50 +++- .../FormTankerCollection.cs | 250 +++++++++++++++--- .../ProjectGasolineTanker/Program.cs | 32 ++- .../ProjectGasolineTanker.csproj | 17 ++ .../ProjectGasolineTanker/serilog.json | 15 ++ 13 files changed, 420 insertions(+), 102 deletions(-) create mode 100644 ProjectGasolineTanker/ProjectGasolineTanker/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectGasolineTanker/ProjectGasolineTanker/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectGasolineTanker/ProjectGasolineTanker/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectGasolineTanker/ProjectGasolineTanker/serilog.json diff --git a/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/AbstractCompany.cs b/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/AbstractCompany.cs index 7e13652..c79246f 100644 --- a/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/AbstractCompany.cs @@ -15,7 +15,7 @@ public abstract class AbstractCompany /// /// Размер места (высота) /// - protected readonly int _placeSizeHeight = 80; + protected readonly int _placeSizeHeight = 97; /// /// Ширина окна @@ -35,7 +35,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); /// /// Конструктор @@ -96,8 +96,13 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningTanker? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningTanker? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (Exception) { } + } return bitmap; diff --git a/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/CarPark.cs b/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/CarPark.cs index 69e4455..56c52b1 100644 --- a/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/CarPark.cs +++ b/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/CarPark.cs @@ -17,8 +17,6 @@ public class CarPark : AbstractCompany protected override void DrawBackground(Graphics g) { - - Pen pen = new Pen(Color.Brown, 3); int offsetX = 10, offsetY = -12; int x = 1 + offsetX, y = _pictureHeight - _placeSizeHeight + offsetY; @@ -49,8 +47,12 @@ public class CarPark : AbstractCompany int row = numRows - 1, col = numCols; for (int i = 0; i < _collection?.Count; i++, col--) { - _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); - _collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9); + try + { + _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9); + } + catch (Exception) { } if (col == 1) { col = numCols + 1; diff --git a/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/ListGenericObjects.cs b/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/ListGenericObjects.cs index d6ede07..ee5b2e0 100644 --- a/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@  +using ProjectGasolineTanker.Exceptions; + namespace ProjectGasolineTanker.CollectionGenericObjects; public class ListGenericObjects : ICollectionGenericObjects where T : class @@ -35,30 +37,24 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= 0 && position < Count) - { - return _collection[position]; - } - else - { - return null; - } - + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + return _collection[position]; } public int Insert(T obj) { - if (Count == _maxCount) { return -1; } + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; } public int Insert(T obj, int position) { - if (position < 0 || position >= Count || Count == _maxCount) - { - return -1; - } + if (position < 0 || position >= Count) + throw new PositionOutOfCollectionException(position); + + if (Count == _maxCount) + throw new CollectionOverflowException(Count); _collection.Insert(position, obj); return position; @@ -66,7 +62,7 @@ public class ListGenericObjects : ICollectionGenericObjects public T Remove(int position) { - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); T obj = _collection[position]; _collection.RemoveAt(position); return obj; @@ -82,4 +78,4 @@ public class ListGenericObjects : ICollectionGenericObjects } ======= >>>>>>> 3ab0f7e (53) -} \ No newline at end of file +} diff --git a/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/MassiveGenericObjects.cs index 917fcf0..9eb1cdb 100644 --- a/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectGasolineTanker.CollectionGenericObjects; +using ProjectGasolineTanker.Exceptions; + +namespace ProjectGasolineTanker.CollectionGenericObjects; public class MassiveGenericObjects : ICollectionGenericObjects where T : class @@ -44,12 +46,9 @@ where T : class public T? Get(int position) { - if (position >= 0 && position < Count) - { - return _collection[position]; - } - - return null; + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); + return _collection[position]; } public int Insert(T obj) @@ -62,14 +61,14 @@ where T : class return i; } } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { if (position < 0 || position >= Count) { - return -1; + throw new PositionOutOfCollectionException(position); } if (_collection[position] == null) { @@ -94,15 +93,16 @@ where T : class } } - return -1; + throw new CollectionOverflowException(Count); } public T Remove(int position) { if (position < 0 || position >= Count) { - return null; + throw new PositionOutOfCollectionException(position); } + if (_collection[position] == null) throw new ObjectNotFoundException(position); T obj = _collection[position]; _collection[position] = null; return obj; @@ -115,4 +115,4 @@ where T : class yield return _collection[i]; } } -} \ No newline at end of file +} diff --git a/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/StorageCollection.cs b/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/StorageCollection.cs index d4a2fb2..1db459d 100644 --- a/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,5 @@ -<<<<<<< HEAD -using ProjectGasolineTanker.Drawnings; +using ProjectGasolineTanker.Drawnings; +using ProjectGasolineTanker.Exceptions; using System.Text; namespace ProjectGasolineTanker.CollectionGenericObjects; @@ -108,11 +108,11 @@ public class StorageCollection /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -148,7 +148,6 @@ public class StorageCollection sb.Clear(); } } - return true; } /// @@ -156,19 +155,21 @@ public class StorageCollection /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } using (StreamReader sr = new StreamReader(filename)) { string? str; str = sr.ReadLine(); + if (str == null || str.Length == 0) + throw new Exception("В файле нет данных"); if (str != _collectionKey.ToString()) - return false; + throw new Exception("В файле неверные данные"); _storages.Clear(); while ((str = sr.ReadLine()) != null) { @@ -181,7 +182,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -191,15 +192,20 @@ public class StorageCollection { if (elem?.CreateDrawningTanker() is T tanker) { - if (collection.Insert(tanker) == -1) - return false; + try + { + if (collection.Insert(tanker) == -1) + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); + } } } _storages.Add(record[0], collection); } } - - return true; } /// @@ -218,4 +224,4 @@ public class StorageCollection } ======= >>>>>>> 3ab0f7e (53) -} \ No newline at end of file +} diff --git a/ProjectGasolineTanker/ProjectGasolineTanker/Exceptions/CollectionOverflowException.cs b/ProjectGasolineTanker/ProjectGasolineTanker/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..dcb5a2d --- /dev/null +++ b/ProjectGasolineTanker/ProjectGasolineTanker/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,17 @@ +using System.Runtime.Serialization; + +namespace ProjectGasolineTanker.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { } + public CollectionOverflowException() : base() { } + public CollectionOverflowException(string message) : base(message) { } + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} + diff --git a/ProjectGasolineTanker/ProjectGasolineTanker/Exceptions/ObjectNotFoundException.cs b/ProjectGasolineTanker/ProjectGasolineTanker/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..bfc7dd5 --- /dev/null +++ b/ProjectGasolineTanker/ProjectGasolineTanker/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectGasolineTanker.Exceptions; + +/// +/// Класс, описывающий ошибку, что по указанной позиции нет элемента +/// +[Serializable] +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + public ObjectNotFoundException() : base() { } + public ObjectNotFoundException(string message) : base(message) { } + public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { } + protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/ProjectGasolineTanker/ProjectGasolineTanker/Exceptions/PositionOutOfCollectionException.cs b/ProjectGasolineTanker/ProjectGasolineTanker/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..6ed687f --- /dev/null +++ b/ProjectGasolineTanker/ProjectGasolineTanker/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectGasolineTanker.Exceptions; + +/// +/// Класс, описывающий ошибку выхода за границы коллекции +/// +[Serializable] +internal class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { } + public PositionOutOfCollectionException() : base() { } + public PositionOutOfCollectionException(string message) : base(message) { } + public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } + protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.Designer.cs b/ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.Designer.cs index 6495386..0fd38ec 100644 --- a/ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.Designer.cs +++ b/ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.Designer.cs @@ -235,19 +235,45 @@ namespace ProjectGasolineTanker pictureBox.TabIndex = 1; pictureBox.TabStop = false; // - // panelCompanyTools + // menuStrip // - panelCompanyTools.Controls.Add(buttonAddTanker); - panelCompanyTools.Controls.Add(maskedTextBoxPosition); - panelCompanyTools.Controls.Add(buttonRefresh); - panelCompanyTools.Controls.Add(buttonRemoveTanker); - panelCompanyTools.Controls.Add(buttonGoToCheck); - panelCompanyTools.Dock = DockStyle.Bottom; - panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 360); - panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(173, 253); - panelCompanyTools.TabIndex = 9; + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1086, 24); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip1"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(48, 20); + файлToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(181, 22); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(181, 22); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; // // FormTankerCollection // diff --git a/ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.cs b/ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.cs index 9aadc20..2566905 100644 --- a/ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.cs +++ b/ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.cs @@ -1,5 +1,7 @@ -using ProjectGasolineTanker.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectGasolineTanker.CollectionGenericObjects; using ProjectGasolineTanker.Drawnings; +using ProjectGasolineTanker.Exceptions; using System.Windows.Forms; namespace ProjectGasolineTanker; @@ -19,13 +21,16 @@ public partial class FormTankerCollection : Form /// private AbstractCompany? _company = null; + private readonly ILogger _logger; /// /// Конструктор /// - public FormTankerCollection() + public FormTankerCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } /// @@ -55,22 +60,27 @@ public partial class FormTankerCollection : Form /// private void SetTanker(DrawningTanker? tank) { - if (_company == null || tank == null) + try { - return; - } + if (_company == null || tank == null) + { + return; + } - if (_company + tank != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if (_company + tank != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + tank.GetDataForSave()); + } } - else + catch (ObjectNotFoundException) { } + catch (CollectionOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show("В коллекции превышено допустимое количество элементов"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } - /// /// Удаление объекта /// @@ -78,25 +88,31 @@ public partial class FormTankerCollection : Form /// private void ButtonRemoveTanker_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) - { - return; - } - - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) - { - return; - } - int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); + if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) + { + throw new Exception("Входные данные отсутствуют"); + } + + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + return; + } + + + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Объект удален"); + } } - else + catch (Exception ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show("Не найден объект по позиции " + pos); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -112,26 +128,34 @@ public partial class FormTankerCollection : Form return; } - DrawningTanker? car = null; + DrawningTanker? tanker = null; int counter = 100; - while (car == null) + try { - car = _company.GetRandomObject(); - counter--; - if (counter <= 0) + while (tanker == null) { - break; + tanker = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } - } - if (car == null) + if (tanker == null) + { + return; + } + + FormGasolineTanker form = new FormGasolineTanker(); + form.SetTanker = tanker; + form.ShowDialog(); + } + catch (Exception ex) { - return; + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - FormGasolineTanker form = new FormGasolineTanker(); - form.SetTanker = car; - form.ShowDialog(); } /// @@ -148,4 +172,152 @@ public partial class FormTankerCollection : Form pictureBox.Image = _company.Show(); } + private void ButtonCollectionAdd_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) + { + MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + try + { + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + RefreshListBoxItems(); + _logger.LogInformation("Добавлена коллекция:", textBoxCollectionName.Text); + } + catch (Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); + } + + } + /// + /// Обновление списка в listBoxCollection + /// + private void RefreshListBoxItems() + { + listBoxCollection.Items.Clear(); + for (int i = 0; i < _storageCollection.Keys?.Count; ++i) + { + string? colName = _storageCollection.Keys?[i]; + if (!string.IsNullOrEmpty(colName)) + { + listBoxCollection.Items.Add(colName); + } + } + + } + + private void ButtonCollectionDel_Click(object sender, EventArgs e) + { + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null) + { + MessageBox.Show("Коллекция не выбрана"); + return; + } + + try + { + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + return; + } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + RefreshListBoxItems(); + _logger.LogInformation("Удалена коллекция: ", listBoxCollection.SelectedItem.ToString()); + } + catch (Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); + } + + } + + + private void ButtonCreateCompany_Click(object sender, EventArgs e) + { + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) + { + MessageBox.Show("Коллекция не выбрана"); + return; + } + + ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + if (collection == null) + { + MessageBox.Show("Коллекция не проинициализирована"); + return; + } + + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new CarPark(pictureBox.Width, pictureBox.Height, collection); + break; + } + + panelCompanyTools.Enabled = true; + RefreshListBoxItems(); + } + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + try + { + _storageCollection.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + + + } + } + + /// + /// Обработка кнопки загрузки + /// + /// + /// + private void LoadToolStripMenuItem_Click(object sender, EventArgs e) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + try + { + _storageCollection.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + RefreshListBoxItems(); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); + } + catch (Exception ex) + { + MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } + } + + } \ No newline at end of file diff --git a/ProjectGasolineTanker/ProjectGasolineTanker/Program.cs b/ProjectGasolineTanker/ProjectGasolineTanker/Program.cs index 913060e..52011af 100644 --- a/ProjectGasolineTanker/ProjectGasolineTanker/Program.cs +++ b/ProjectGasolineTanker/ProjectGasolineTanker/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace ProjectGasolineTanker { internal static class Program @@ -11,7 +16,32 @@ namespace ProjectGasolineTanker // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormTankerCollection()); + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + /// + /// DI + /// + /// + private static void ConfigureServices(ServiceCollection services) + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(new ConfigurationBuilder(). + AddJsonFile($"{pathNeed}serilog.json").Build()).CreateLogger()); + }); } } } \ No newline at end of file diff --git a/ProjectGasolineTanker/ProjectGasolineTanker/ProjectGasolineTanker.csproj b/ProjectGasolineTanker/ProjectGasolineTanker/ProjectGasolineTanker.csproj index e1a0735..510d0d2 100644 --- a/ProjectGasolineTanker/ProjectGasolineTanker/ProjectGasolineTanker.csproj +++ b/ProjectGasolineTanker/ProjectGasolineTanker/ProjectGasolineTanker.csproj @@ -8,4 +8,21 @@ enable + + + + + + + + + + + + + + Always + + + \ No newline at end of file diff --git a/ProjectGasolineTanker/ProjectGasolineTanker/serilog.json b/ProjectGasolineTanker/ProjectGasolineTanker/serilog.json new file mode 100644 index 0000000..b947cc8 --- /dev/null +++ b/ProjectGasolineTanker/ProjectGasolineTanker/serilog.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "log.log" } + } + ], + "Properties": { + "Applicatoin": "Sample" + } + } +} \ No newline at end of file