From a3e707a26c5957cda79967bf43580371c061a648 Mon Sep 17 00:00:00 2001
From: Garifullin-Farid <95081032+Garifullin-Farid@users.noreply.github.com>
Date: Mon, 20 May 2024 01:43:27 +0400
Subject: [PATCH] LabWork_7
---
.../ListGenericObjects.cs | 70 ++++--
.../MassiveGenericObjects.cs | 228 ++++++++----------
.../StorageCollection.cs | 101 ++++----
.../CollectionGenericObjects/TankBase.cs | 2 +-
.../Exceptions/CollectionOverflowException.cs | 16 ++
.../Exceptions/ObjectNotFoundException.cs | 16 ++
.../PositionOutOfCollectionException.cs | 16 ++
.../FormBattleTankCollection.Designer.cs | 10 +-
.../ProjectTank/FormBattleTankCollection.cs | 178 +++++++++-----
ProjectTank/ProjectTank/Program.cs | 33 ++-
ProjectTank/ProjectTank/ProjectTank.csproj | 59 +++--
ProjectTank/ProjectTank/serilog.json | 20 ++
12 files changed, 471 insertions(+), 278 deletions(-)
create mode 100644 ProjectTank/ProjectTank/Exceptions/CollectionOverflowException.cs
create mode 100644 ProjectTank/ProjectTank/Exceptions/ObjectNotFoundException.cs
create mode 100644 ProjectTank/ProjectTank/Exceptions/PositionOutOfCollectionException.cs
create mode 100644 ProjectTank/ProjectTank/serilog.json
diff --git a/ProjectTank/ProjectTank/CollectionGenericObjects/ListGenericObjects.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/ListGenericObjects.cs
index f683a7d..fa6605d 100644
--- a/ProjectTank/ProjectTank/CollectionGenericObjects/ListGenericObjects.cs
+++ b/ProjectTank/ProjectTank/CollectionGenericObjects/ListGenericObjects.cs
@@ -1,6 +1,9 @@
-using ProjectTank.CollectionGenericObjects;
+using ProjectTank.Exceptions;
+
+namespace ProjectTank.CollectionGenericObjects;
+
///
/// Параметризованный набор объектов
///
@@ -12,14 +15,20 @@ public class ListGenericObjects : ICollectionGenericObjects
/// Список объектов, которые храним
///
private readonly List _collection;
+
///
/// Максимально допустимое число объектов в списке
///
private int _maxCount;
+
public int Count => _collection.Count;
+
public int MaxCount
{
- get => _maxCount;
+ get
+ {
+ return _collection.Count;
+ }
set
{
if (value > 0)
@@ -29,7 +38,6 @@ public class ListGenericObjects : ICollectionGenericObjects
}
}
-
public CollectionType GetCollectionType => CollectionType.List;
///
@@ -39,47 +47,63 @@ public class ListGenericObjects : ICollectionGenericObjects
{
_collection = new();
}
+
+
public T? Get(int position)
{
- if (position <= Count)
+ // TODO проверка позиции
+ if (position >= Count || position < 0)
{
- return _collection[position];
+ throw new PositionOutOfCollectionException(position);
}
- else
- return null;
+ return _collection[position];
}
+
public int Insert(T obj)
{
- if (Count + 1 > _maxCount)
+ // TODO проверка, что не превышено максимальное количество элементов
+ if (Count == _maxCount)
{
- return -1;
- }
+ throw new CollectionOverflowException(Count);
+ }
+ // TODO вставка в конец набора
_collection.Add(obj);
- return Count;
+ return _collection.Count;
}
public int Insert(T obj, int position)
{
- if (Count + 1 > _maxCount)
- return -1;
- if (position < 0 || position > Count)
- return -1;
+ // TODO проверка, что не превышено максимальное количество элементов
+ if (Count == _maxCount)
+ {
+ throw new CollectionOverflowException(Count);
+ }
+ // TODO проверка позиции
+ if (position >= Count || position < 0)
+ {
+ throw new PositionOutOfCollectionException(position);
+ }
+ // TODO вставка по позиции
_collection.Insert(position, obj);
- return 1;
-
+ return position;
}
public T? Remove(int position)
{
- if (position < 0 || position > Count)
- return null;
- T? temp = _collection[position];
+ // TODO проверка позиции
+ if (position >= Count || position < 0)
+ {
+ throw new PositionOutOfCollectionException(position);
+ }
+ // TODO удаление объекта из списка
+ T? obj = _collection[position];
_collection.RemoveAt(position);
- return temp;
+ return obj;
}
+
public IEnumerable GetItems()
{
- for (int i = 0; i < Count; i++)
+ for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
-}
\ No newline at end of file
+}
diff --git a/ProjectTank/ProjectTank/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/MassiveGenericObjects.cs
index 32ea0fd..228d8ea 100644
--- a/ProjectTank/ProjectTank/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/ProjectTank/ProjectTank/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -1,149 +1,133 @@
using ProjectTank.CollectionGenericObjects;
+using ProjectTank.Exceptions;
///
/// Параметризованный набор объектов
///
/// Параметр: ограничение - ссылочный тип
-public class MassiveGenericObjects : ICollectionGenericObjects
- where T : class
-{
- ///
- /// Массив объектов, которые храним
- ///
- private T?[] _collection;
- public int Count => _collection.Length;
- public int MaxCount
+ public class MassiveGenericObjects : ICollectionGenericObjects
+ where T : class
{
- get
+ ///
+ /// Массив объектов, которые храним
+ ///
+ private T?[] _collection;
+
+ public int Count => _collection.Length;
+
+ public int MaxCount
{
- return _collection.Length;
- }
- set
- {
- if (value > 0)
+ get
{
- if (Count > 0)
- {
- Array.Resize(ref _collection, value);
- }
- else
- {
- _collection = new T?[value];
- }
+ return _collection.Length;
}
- }
- }
- public CollectionType GetCollectionType => CollectionType.Massive;
-
- public int SetMaxCount {
- set
- {
- if (value > 0)
+ set
{
- if (_collection.Length > 0)
+ if (value > 0)
{
- Array.Resize(ref _collection, value);
- }
- else
- {
- _collection = new T?[value];
- }
- }
- }
- }
- //public CollectionType GetCollectionType => CollectionType.Massive;
-
- ///
- /// Конструктор
- ///
- public MassiveGenericObjects()
- {
- _collection = Array.Empty();
- }
-
- public T? Get(int position)
- {
- if (position >= 0 && position < Count)
- {
- return _collection[position];
- }
-
- return null;
- }
-
- public int Insert(T obj)
- {
- // вставка в свободное место набора
- return Insert(obj, 0);
- }
-
- public int Insert(T obj, int position)
- {
- // проверка позиции
- if (position < 0 || position >= Count)
- {
- return -1;
- }
-
- // проверка, что элемент массива по этой позиции пустой, если нет, то
- // ищется свободное место после этой позиции и идет вставка туда
- // если нет после, ищем до
- if (_collection[position] != null)
- {
- bool pushed = false;
- for (int index = position + 1; index < Count; index++)
- {
- if (_collection[index] == null)
- {
- position = index;
- pushed = true;
- break;
- }
- }
-
- if (!pushed)
- {
- for (int index = position - 1; index >= 0; index--)
- {
- if (_collection[index] == null)
+ if (_collection.Length > 0)
{
- position = index;
- pushed = true;
- break;
+ Array.Resize(ref _collection, value);
+ }
+ else
+ {
+ _collection = new T?[value];
}
}
}
+ }
- if (!pushed)
+ public CollectionType GetCollectionType => CollectionType.Massive;
+
+ ///
+ /// Конструктор
+ ///
+ public MassiveGenericObjects()
+ {
+ _collection = Array.Empty();
+ }
+
+ public T? Get(int position)
+ {
+ // TODO проверка позиции
+ if (position < 0 || position > _collection.Length)
{
+ throw new PositionOutOfCollectionException(position);
+ }
+ if (position >= Count && _collection[position] == null)
+ {
+ throw new ObjectNotFoundException(position);
+ }
+ return _collection[position];
+ }
+
+ public int Insert(T obj)
+ {
+
+ return Insert(obj,0);
+ throw new CollectionOverflowException(Count);
+ }
+
+ public int Insert(T obj, int position)
+ {
+ // TODO проверка позиции
+ if (position > _collection.Length || position < 0)
+ {
+ throw new PositionOutOfCollectionException(position);
+ }
+ // TODO проверка, что элемент массива по этой позиции пустой, если нет, то
+ // ищется свободное место после этой позиции и идет вставка туда
+ // если нет после, ищем до
+ if (_collection[position] == null)
+ {
+ _collection[position] = obj;
return position;
}
+
+ for (int tmp = position + 1; tmp < _collection.Length; tmp++)
+ {
+ if (_collection[tmp] == null)
+ {
+ _collection[tmp] = obj;
+ return tmp;
+ }
+ }
+
+ for (int tmp = position - 1; tmp >= 0; tmp--)
+ {
+ if (_collection[tmp] == null)
+ {
+ _collection[tmp] = obj;
+ return tmp;
+ }
+ }
+
+ throw new CollectionOverflowException(Count);
}
- // вставка
- _collection[position] = obj;
- return position;
- }
-
- public T? Remove(int position)
- {
- // проверка позиции
- if (position < 0 || position >= Count)
+ public T? Remove(int position)
{
- return null;
+ // TODO проверка позиции
+ if (position < 0 || position > _collection.Length)
+ {
+ throw new PositionOutOfCollectionException(position);
+ }
+
+ if (_collection[position] == null)
+ {
+ throw new ObjectNotFoundException(position);
+ }
+ T? tmp = _collection[position];
+ _collection[position] = null;
+ // TODO удаление объекта из массива, присвоив элементу массива значение null
+ return tmp;
}
- if (_collection[position] == null) return null;
-
- T? temp = _collection[position];
- _collection[position] = null;
- return temp;
- }
- public IEnumerable GetItems()
- {
- for (int i = 0; i < _collection.Length; i++)
+ public IEnumerable GetItems()
{
- yield return _collection[i];
+ for (int i = 0; i < _collection.Length; ++i)
+ {
+ yield return _collection[i];
+ }
}
- }
-}
\ No newline at end of file
+ }
\ No newline at end of file
diff --git a/ProjectTank/ProjectTank/CollectionGenericObjects/StorageCollection.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/StorageCollection.cs
index 983b5a6..97c8a9b 100644
--- a/ProjectTank/ProjectTank/CollectionGenericObjects/StorageCollection.cs
+++ b/ProjectTank/ProjectTank/CollectionGenericObjects/StorageCollection.cs
@@ -1,5 +1,6 @@
using ProjectTank.Drawning;
+using ProjectTank.Exceptions;
using System.Text;
namespace ProjectTank.CollectionGenericObjects
@@ -90,11 +91,11 @@ namespace ProjectTank.CollectionGenericObjects
return _storages[name];
}
}
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (_storages.Count == 0)
{
- return false;
+ throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@@ -102,78 +103,66 @@ namespace ProjectTank.CollectionGenericObjects
File.Delete(filename);
}
- using (StreamWriter writer = new StreamWriter(filename))
+ using FileStream fs = new(filename, FileMode.Create);
+ using StreamWriter sw = new StreamWriter(fs);
+ sw.WriteLine(_collectionKey);
+ foreach (KeyValuePair> value in _storages)
{
- writer.Write(_collectionKey);
- foreach (KeyValuePair> value in _storages)
+ sw.Write(Environment.NewLine);
+ // не сохраняем пустые коллекции
+ if (value.Value.Count == 0)
{
- StringBuilder sb = new();
+ continue;
+ }
+ sw.Write(value.Key);
+ sw.Write(_separatorForKeyValue);
+ sw.Write(value.Value.GetCollectionType);
+ sw.Write(_separatorForKeyValue);
+ sw.Write(value.Value.MaxCount);
+ sw.Write(_separatorForKeyValue);
- sb.Append(Environment.NewLine);
- // не сохраняем пустые коллекции
- if (value.Value.Count == 0)
+
+ foreach (T? item in value.Value.GetItems())
+ {
+ string data = item?.GetDataForSave() ?? string.Empty;
+ if (string.IsNullOrEmpty(data))
{
continue;
}
- sb.Append(value.Key);
- sb.Append(_separatorForKeyValue);
- sb.Append(value.Value.GetCollectionType);
- sb.Append(_separatorForKeyValue);
- sb.Append(value.Value.MaxCount);
- sb.Append(_separatorForKeyValue);
-
- foreach (T? item in value.Value.GetItems())
- {
- string data = item?.GetDataForSave() ?? string.Empty;
- if (string.IsNullOrEmpty(data))
- {
- continue;
- }
-
- sb.Append(data);
- sb.Append(_separatorItems);
- }
-
- writer.Write(sb);
+ sw.Write(data);
+ sw.Write(_separatorItems);
}
-
}
-
- return true;
}
///
- /// Загрузка информации по автомобилям в хранилище из файла
+ /// Загрузка информации по локомотивам в хранилище из файла
///
/// Путь и имя файла
/// true - загрузка прошла успешно, false - ошибка при загрузке данных
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new FileNotFoundException("Файл не существует");
}
- using (StreamReader fs = File.OpenText(filename))
+ using (StreamReader reader = new(filename))
{
- string str = fs.ReadLine();
-
- if (str == null || str.Length == 0)
+ string line = reader.ReadLine();
+ if (line == null || line.Length == 0)
{
- return false;
+ throw new InvalidDataException("В файле нет данных");
}
-
- if (!str.StartsWith(_collectionKey))
+ if (!line.Equals(_collectionKey))
{
- return false;
+ throw new InvalidOperationException("В файле неверные данные");
}
-
_storages.Clear();
- string strs = "";
- while ((strs = fs.ReadLine()) != null)
+ while ((line = reader.ReadLine()) != null)
{
- string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
+ string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
@@ -183,7 +172,7 @@ namespace ProjectTank.CollectionGenericObjects
ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType);
if (collection == null)
{
- return false;
+ throw new InvalidOperationException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
@@ -191,20 +180,28 @@ namespace ProjectTank.CollectionGenericObjects
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
- if (elem?.CreateDrawningTank() is T airbus)
+ if (elem?.CreateDrawningTank() is T locomotive)
{
- if (collection.Insert(airbus) == -1)
+ try
{
- return false;
+ if (collection.Insert(locomotive) == -1)
+ {
+ throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
+ }
+ }
+ catch (CollectionOverflowException ex)
+ {
+ throw new ArgumentOutOfRangeException("Коллекция переполнена", ex);
}
}
+
}
_storages.Add(record[0], collection);
}
- return true;
}
}
+
///
/// Создание коллекции по типа
///
diff --git a/ProjectTank/ProjectTank/CollectionGenericObjects/TankBase.cs b/ProjectTank/ProjectTank/CollectionGenericObjects/TankBase.cs
index 3840c02..990e899 100644
--- a/ProjectTank/ProjectTank/CollectionGenericObjects/TankBase.cs
+++ b/ProjectTank/ProjectTank/CollectionGenericObjects/TankBase.cs
@@ -31,7 +31,7 @@ namespace ProjectTank.CollectionGenericObjects
int TankWidth = 0;
int TankHeight = 0;
- for (int i = 0; i < (_collection?.Count ?? 0); i++)
+ for (int i = 0; i < (_collection?.Count); i++)
{
if (_collection?.Get(i) != null)
{
diff --git a/ProjectTank/ProjectTank/Exceptions/CollectionOverflowException.cs b/ProjectTank/ProjectTank/Exceptions/CollectionOverflowException.cs
new file mode 100644
index 0000000..0790154
--- /dev/null
+++ b/ProjectTank/ProjectTank/Exceptions/CollectionOverflowException.cs
@@ -0,0 +1,16 @@
+using System.Runtime.Serialization;
+
+namespace ProjectTank.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/ProjectTank/ProjectTank/Exceptions/ObjectNotFoundException.cs b/ProjectTank/ProjectTank/Exceptions/ObjectNotFoundException.cs
new file mode 100644
index 0000000..c970af4
--- /dev/null
+++ b/ProjectTank/ProjectTank/Exceptions/ObjectNotFoundException.cs
@@ -0,0 +1,16 @@
+using System.Runtime.Serialization;
+
+namespace ProjectTank.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/ProjectTank/ProjectTank/Exceptions/PositionOutOfCollectionException.cs b/ProjectTank/ProjectTank/Exceptions/PositionOutOfCollectionException.cs
new file mode 100644
index 0000000..52c64fe
--- /dev/null
+++ b/ProjectTank/ProjectTank/Exceptions/PositionOutOfCollectionException.cs
@@ -0,0 +1,16 @@
+using System.Runtime.Serialization;
+
+namespace ProjectTank.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) { }
+}
diff --git a/ProjectTank/ProjectTank/FormBattleTankCollection.Designer.cs b/ProjectTank/ProjectTank/FormBattleTankCollection.Designer.cs
index 7e189c4..49d941c 100644
--- a/ProjectTank/ProjectTank/FormBattleTankCollection.Designer.cs
+++ b/ProjectTank/ProjectTank/FormBattleTankCollection.Designer.cs
@@ -68,9 +68,9 @@ namespace ProjectTank
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
- groupBoxTools.Location = new Point(798, 24);
+ groupBoxTools.Location = new Point(824, 24);
groupBoxTools.Name = "groupBoxTools";
- groupBoxTools.Size = new Size(187, 611);
+ groupBoxTools.Size = new Size(187, 623);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "инструменты";
@@ -250,7 +250,7 @@ namespace ProjectTank
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
- pictureBox.Size = new Size(798, 611);
+ pictureBox.Size = new Size(824, 623);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@@ -259,7 +259,7 @@ namespace ProjectTank
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
- menuStrip.Size = new Size(985, 24);
+ menuStrip.Size = new Size(1011, 24);
menuStrip.TabIndex = 8;
menuStrip.Text = "menuStrip";
//
@@ -298,7 +298,7 @@ namespace ProjectTank
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
- ClientSize = new Size(985, 635);
+ ClientSize = new Size(1011, 647);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
diff --git a/ProjectTank/ProjectTank/FormBattleTankCollection.cs b/ProjectTank/ProjectTank/FormBattleTankCollection.cs
index 689201b..39ddb6c 100644
--- a/ProjectTank/ProjectTank/FormBattleTankCollection.cs
+++ b/ProjectTank/ProjectTank/FormBattleTankCollection.cs
@@ -1,5 +1,7 @@
+using Microsoft.Extensions.Logging;
using ProjectTank.CollectionGenericObjects;
using ProjectTank.Drawning;
+using ProjectTank.Exceptions;
namespace ProjectTank
{
@@ -12,18 +14,23 @@ namespace ProjectTank
/// Хранилище коллекций
///
private readonly StorageCollection _storageCollection;
+
+
///
/// Компания
///
private AbstractCompany? _company = null;
+ private readonly ILogger _logger;
///
/// Конструктор
///
- public FormBattleTankCollection()
+ public FormBattleTankCollection(ILogger logger)
{
InitializeComponent();
_storageCollection = new();
+ _logger = logger;
+ _logger.LogInformation("Форма загрузилась");
}
///
@@ -42,17 +49,28 @@ namespace ProjectTank
/// Тип создоваемого объекта
private void SetTank(DrawningTank tank)
{
- if (_company == null || tank == null)
+ if (_company == null || tank == null)
+ {
return;
-
- if (_company + tank != -1)
- {
- MessageBox.Show("Объект добавлен");
- pictureBox.Image = _company.Show();
}
- else
+ try
{
- MessageBox.Show("Не удалось добавить объект");
+ if (_company + tank >= 0)
+ {
+ MessageBox.Show("Объект добавлен");
+ pictureBox.Image = _company.Show();
+ _logger.LogInformation("Объект добавлен: " + tank.GetDataForSave());
+ }
+ }
+ catch (CollectionOverflowException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
+ catch (ObjectNotFoundException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -76,20 +94,34 @@ namespace ProjectTank
private void buttonRemoveTank_Click(object sender, EventArgs e)
{
- if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) return;
-
- if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
-
- int position = Convert.ToInt32(maskedTextBox.Text);
-
- if (_company - position != null)
+ if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
- MessageBox.Show("Объект удален");
- pictureBox.Image = _company.Show();
+ return;
}
- else
+
+ if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
- MessageBox.Show("Не удалось удалить объект");
+ return;
+ }
+ int pos = Convert.ToInt32(maskedTextBox.Text);
+ try
+ {
+ if (_company - pos != null)
+ {
+ MessageBox.Show("Объект удален");
+ pictureBox.Image = _company.Show();
+ _logger.LogInformation("Объект удален, позиция: " + pos);
+ }
+ }
+ catch (ObjectNotFoundException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
+ catch (PositionOutOfCollectionException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
///
@@ -99,20 +131,38 @@ namespace ProjectTank
///
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
- if (_company == null) return;
-
+ if (_company == null)
+ {
+ return;
+ }
DrawningTank? tank = null;
- int coutner = 100;
-
+ int counter = 100;
while (tank == null)
{
- tank = _company.GetRandomObject();
- coutner--;
- if (coutner <= 0) break;
+ try
+ {
+ tank = _company.GetRandomObject();
+ counter--;
+ if (counter <= 0)
+ {
+ break;
+ }
+ }
+ catch (ObjectNotFoundException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
+ catch (PositionOutOfCollectionException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
+ }
+ if (tank == null)
+ {
+ return;
}
-
- if (tank == null) return;
-
FormBattleTank form = new()
{
SetTank = tank
@@ -141,19 +191,26 @@ namespace ProjectTank
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
-
- CollectionType collectionType = CollectionType.None;
- if (radioButtonMassive.Checked)
+ try
{
- collectionType = CollectionType.Massive;
+ CollectionType collectionType = CollectionType.None;
+ if (radioButtonMassive.Checked)
+ {
+ collectionType = CollectionType.Massive;
+ }
+ else if (radioButtonList.Checked)
+ {
+ collectionType = CollectionType.List;
+ }
+ _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
+ RerfreshListBoxItems();
+ _logger.LogInformation("Коллекция добавлена: " + textBoxCollectionName.Text);
}
- else if (radioButtonList.Checked)
+ catch (Exception ex)
{
- collectionType = CollectionType.List;
+ //MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
-
- _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
- RerfreshListBoxItems();
}
///
@@ -163,17 +220,24 @@ namespace ProjectTank
///
private void buttonCollectionDel_Click(object sender, EventArgs e)
{
- if (listBoxСollection.SelectedIndex < 0 || listBoxСollection.SelectedItem == null)
- {
- MessageBox.Show("Коллекция не выбрана");
- return;
- }
- if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
+ if (!radioButtonList.Checked && !radioButtonMassive.Checked || string.IsNullOrEmpty(textBoxCollectionName.Text))
{
return;
}
- _storageCollection.DelCollection(listBoxСollection.SelectedItem.ToString());
- RerfreshListBoxItems();
+ try
+ {
+ if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
+ {
+ return;
+ }
+ _storageCollection.DelCollection(listBoxСollection.SelectedItem.ToString());
+ RerfreshListBoxItems();
+ _logger.LogInformation("Коллекция удалена: " + listBoxСollection.SelectedItem.ToString());
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
}
///
/// Обновление списка в listBoxCollection
@@ -225,13 +289,17 @@ namespace ProjectTank
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storageCollection.SaveData(saveFileDialog.FileName))
+ try
{
+ _storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
+
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@@ -245,15 +313,17 @@ namespace ProjectTank
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storageCollection.LoadData(openFileDialog.FileName))
+ try
{
+ _storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
+ _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
-
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
diff --git a/ProjectTank/ProjectTank/Program.cs b/ProjectTank/ProjectTank/Program.cs
index 4b02a00..f19e1c4 100644
--- a/ProjectTank/ProjectTank/Program.cs
+++ b/ProjectTank/ProjectTank/Program.cs
@@ -1,3 +1,8 @@
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Configuration;
+using Serilog;
+
namespace ProjectTank
{
internal static class Program
@@ -11,7 +16,33 @@ namespace ProjectTank
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
- Application.Run(new FormBattleTankCollection());
+ ServiceCollection services = new();
+ ConfigureServices(services);
+ using ServiceProvider serviceProvider = services.BuildServiceProvider();
+ Application.Run(serviceProvider.GetRequiredService());
+ }
+
+ ///
+ /// Êîíôèãóðàöèÿ ñåðâèñà DI
+ ///
+ ///
+ private static void ConfigureServices(ServiceCollection services)
+ {
+ services.AddSingleton().AddLogging(option =>
+ {
+ var configuration = new ConfigurationBuilder()
+ .SetBasePath(Directory.GetCurrentDirectory())
+ .AddJsonFile(path: "serilog.json", optional: false, reloadOnChange: true)
+ .Build();
+
+ var logger = new LoggerConfiguration()
+ .ReadFrom.Configuration(configuration)
+ .CreateLogger();
+
+ option.SetMinimumLevel(LogLevel.Information);
+ option.AddSerilog(logger);
+
+ });
}
}
}
\ No newline at end of file
diff --git a/ProjectTank/ProjectTank/ProjectTank.csproj b/ProjectTank/ProjectTank/ProjectTank.csproj
index 244387d..4c59756 100644
--- a/ProjectTank/ProjectTank/ProjectTank.csproj
+++ b/ProjectTank/ProjectTank/ProjectTank.csproj
@@ -1,26 +1,45 @@
-
- WinExe
- net7.0-windows
- enable
- true
- enable
-
+
+ WinExe
+ net7.0-windows
+ enable
+ true
+ enable
+
-
-
- True
- True
- Resources.resx
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-
-
- ResXFileCodeGenerator
- Resources.Designer.cs
-
-
+
+
+ True
+ True
+ Resources.resx
+
+
+
+
+
+ ResXFileCodeGenerator
+ Resources.Designer.cs
+
+
+
+
+
+ Always
+
+
\ No newline at end of file
diff --git a/ProjectTank/ProjectTank/serilog.json b/ProjectTank/ProjectTank/serilog.json
new file mode 100644
index 0000000..b83a37c
--- /dev/null
+++ b/ProjectTank/ProjectTank/serilog.json
@@ -0,0 +1,20 @@
+{
+ "Serilog": {
+ "Using": [ "Serilog.Sinks.File" ],
+ "MinimumLevel": "Information",
+ "WriteTo": [
+ {
+ "Name": "File",
+ "Args": {
+ "path": "Logs/log_.log",
+ "rollingInterval": "Day",
+ "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
+ }
+ }
+ ],
+ "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
+ "Properties": {
+ "Application": "BattleTank"
+ }
+ }
+}