diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs
index 481d134..2629ae6 100644
--- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs
+++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/AbstractCompany.cs
@@ -1,4 +1,5 @@
using ProjectBattleship.DrawingObject;
+using ProjectBattleship.Exceptions;
namespace ProjectBattleship.CollectionGenericObjects;
///
@@ -30,8 +31,7 @@ public abstract class AbstractCompany
/// Вычисление максимального количества элементов, который можно
/// разместить в окне
///
- private int GetMaxCount => _pictureWidth * _pictureHeight /
- (_placeSizeWidth * _placeSizeHeight);
+ private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
///
/// Конструктор
///
@@ -85,20 +85,30 @@ public abstract class AbstractCompany
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
- DrawBackgound(graphics);
+ DrawBackground(graphics);
+
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
- DrawingWarship? obj = _collection?.Get(i);
- obj?.DrawTransport(graphics);
+ try
+ {
+ DrawingWarship? obj = _collection?.Get(i);
+ obj?.DrawTransport(graphics);
+ }
+ catch (ObjectNotFoundException e)
+ { }
+ catch (PositionOutOfCollectionException e)
+ { }
}
+
return bitmap;
}
+
///
/// Вывод заднего фона
///
///
- protected abstract void DrawBackgound(Graphics g);
+ protected abstract void DrawBackground(Graphics g);
///
/// Расстановка объектов
///
diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/Docks.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/Docks.cs
index 5535ff2..a486f47 100644
--- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/Docks.cs
+++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/Docks.cs
@@ -1,4 +1,5 @@
using ProjectBattleship.DrawingObject;
+using ProjectBattleship.Exceptions;
namespace ProjectBattleship.CollectionGenericObjects;
///
@@ -12,12 +13,12 @@ public class Docks : AbstractCompany
///
///
///
- public Docks(int picWidth, int picHeight,
- ICollectionGenericObjects collection) :
+ public Docks(int picWidth, int picHeight,
+ ICollectionGenericObjects collection) :
base(picWidth, picHeight, collection)
{
}
- protected override void DrawBackgound(Graphics g)
+ protected override void DrawBackground(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
@@ -26,48 +27,47 @@ public class Docks : AbstractCompany
{
for (int j = 0; j < height; ++j)
{
- g.FillRectangle(brush, i * _placeSizeWidth,
+ g.FillRectangle(brush, i * _placeSizeWidth,
j * _placeSizeHeight, 200, 5);
- g.FillRectangle(brush, i * _placeSizeWidth,
+ g.FillRectangle(brush, i * _placeSizeWidth,
j * _placeSizeHeight, 5, 80);
}
}
for (int j = 0; j < height - 4; ++j)
{
- g.FillRectangle(brush, j * _placeSizeWidth,
+ g.FillRectangle(brush, j * _placeSizeWidth,
height * _placeSizeHeight, 200, 5);
}
}
protected override void SetObjectsPosition()
{
- if (_collection == null) return;
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int curWidth = width - 1;
int curHeight = 0;
- for (int i = 0; i < _collection.Count; i++)
+ for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
- DrawingWarship? _warship = _collection.Get(i);
- if (_warship != null)
+ try
{
- if (_warship.SetPictureSize(_pictureWidth, _pictureHeight))
- {
- _warship.SetPosition(_placeSizeWidth * curWidth + 20,
- curHeight * _placeSizeHeight + 15);
- }
+ _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
+ _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
}
- curWidth--;
- if (curWidth < 0)
+ catch (ObjectNotFoundException) { }
+ catch (PositionOutOfCollectionException e) { }
+ if (curWidth > 0)
+ curWidth--;
+ else
{
- curHeight++;
curWidth = width - 1;
+ curHeight++;
}
+
if (curHeight >= height)
{
return;
}
}
}
-}
+}
\ No newline at end of file
diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs
index f719f85..cc604f8 100644
--- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs
+++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/ListGenericObjects.cs
@@ -1,4 +1,9 @@
-namespace ProjectBattleship.CollectionGenericObjects;
+using ProjectBattleship.CollectionGenericObjects;
+using ProjectBattleship.Exceptions;
+
+
+namespace Battleship.CollectionGenericObjects;
+
///
/// Параметризованный набор объектов
///
@@ -16,7 +21,21 @@ where T : class
private int _maxCount;
public int Count => _collection.Count;
- public int MaxCount { set { if (value > 0) { _maxCount = value; } } get { return Count; } }
+ public int MaxCount
+ {
+ set
+ {
+ if (value > 0)
+ {
+ _maxCount = value;
+ }
+ }
+ get
+ {
+
+ return Count;
+ }
+ }
public CollectionType GetCollectionType => CollectionType.List;
@@ -27,41 +46,33 @@ where T : class
{
_collection = new();
}
- public T? Get(int position)
+ public T Get(int position)
{
- if (position >= 0 && position < Count)
- {
- return _collection[position];
- }
- return null;
+ if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
+ return _collection[position];
}
+
public int Insert(T obj)
{
- if (Count <= _maxCount)
- {
- _collection.Add(obj);
- return Count;
- }
- return -1;
+ if (Count == _maxCount) throw new CollectionOverflowException(Count);
+ _collection.Add(obj);
+ return Count;
}
+
public int Insert(T obj, int position)
{
- if (Count < _maxCount && position >= 0 && position < _maxCount)
- {
- _collection.Insert(position, obj);
- return position;
- }
- return -1;
+ if (Count == _maxCount) throw new CollectionOverflowException(Count);
+ if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
+ _collection.Insert(position, obj);
+ return position;
}
+
public T Remove(int position)
{
- T temp = _collection[position];
- if (position >= 0 && position < _maxCount)
- {
- _collection.RemoveAt(position);
- return temp;
- }
- return null;
+ if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
+ T obj = _collection[position];
+ _collection.RemoveAt(position);
+ return obj;
}
public IEnumerable GetItems()
diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs
index d6e9692..913bfc2 100644
--- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -1,18 +1,22 @@
-namespace ProjectBattleship.CollectionGenericObjects;
+using ProjectBattleship.Exceptions;
+using ProjectBattleship.CollectionGenericObjects;
+
+namespace Battleship.CollectionGenericObjects;
///
/// Параметризованный набор объектов
///
/// Параметр: ограничение - ссылочный тип
public class MassiveGenericObjects : ICollectionGenericObjects
-where T : class
+ where T : class
{
///
/// Массив объектов, которые храним
///
private T?[] _collection;
-
public int Count => _collection.Length;
-
+ ///
+ /// Установка максимального кол-ва объектов
+ ///
public int MaxCount
{
get
@@ -44,69 +48,86 @@ where T : class
{
_collection = Array.Empty();
}
+ ///
+ /// Получение объекта по позиции
+ ///
+ /// Позиция (индекс)
+ ///
public T? Get(int position)
{
- if (position >= _collection.Length || position < 0)
- {
- return null;
- }
+ if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
+ if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
+
public int Insert(T obj)
{
- int index = 0;
- while (index < _collection.Length)
+ // вставка в свободное место набора
+ for (int i = 0; i < Count; i++)
{
- if (_collection[index] == null)
+ if (_collection[i] == null)
{
- _collection[index] = obj;
- return index;
+ _collection[i] = obj;
+ return i;
}
- index++;
}
- return -1;
+
+ throw new CollectionOverflowException(Count);
}
+
public int Insert(T obj, int position)
{
+ // проверка позиции
+ if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
- if (position >= _collection.Length || position < 0)
- { return -1; }
-
- if (_collection[position] == null)
+ if (_collection[position] != null)
{
- _collection[position] = obj;
- return position;
- }
- int index;
-
- for (index = position + 1; index < _collection.Length; ++index)
- {
- if (_collection[index] == null)
+ bool pushed = false;
+ for (int index = position + 1; index < Count; index++)
{
- _collection[position] = obj;
- return position;
+ if (_collection[index] == null)
+ {
+ position = index;
+ pushed = true;
+ break;
+ }
+ }
+
+ if (!pushed)
+ {
+ for (int index = position - 1; index >= 0; index--)
+ {
+ if (_collection[index] == null)
+ {
+ position = index;
+ pushed = true;
+ break;
+ }
+ }
+ }
+
+ if (!pushed)
+ {
+ throw new CollectionOverflowException(Count);
}
}
- for (index = position - 1; index >= 0; --index)
- {
- if (_collection[index] == null)
- {
- _collection[position] = obj;
- return position;
- }
- }
- return -1;
+ // вставка
+ _collection[position] = obj;
+ return position;
}
- public T Remove(int position)
+
+ public T? Remove(int position)
{
- if (position >= _collection.Length || position < 0)
- { return null; }
- T DrawningWarship = _collection[position];
- _collection[position] = null;
- return DrawningWarship;
- }
+ // проверка позиции
+ if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
+ if (_collection[position] == null) throw new ObjectNotFoundException(position);
+
+ T? temp = _collection[position];
+ _collection[position] = null;
+ return temp;
+ }
public IEnumerable GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
diff --git a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs
index 4cbf3e0..6c2b498 100644
--- a/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs
+++ b/ProjectBattleship/ProjectBattleship/CollectionGenericObjects/StorageCollection.cs
@@ -1,12 +1,14 @@
-using ProjectBattleship.DrawingObject;
+using ProjectBattleship.CollectionGenericObjects;
+using ProjectBattleship.DrawingObject;
+using ProjectBattleship.Exceptions;
+
+namespace Battleship.CollectionGenericObjects;
-namespace ProjectBattleship.CollectionGenericObjects;
///
/// Класс-хранилище коллекций
///
///
-public class StorageCollection
-where T : DrawingWarship
+public class StorageCollection where T : DrawingWarship
{
///
/// Словарь (хранилище) с коллекциями
@@ -44,20 +46,23 @@ where T : DrawingWarship
///
/// Название коллекции
/// тип коллекции
- public void AddCollection(string name, CollectionType collectionType)
+ public void AddCollection(string name, CollectionType collectionType)
{
- if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name))
+ if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
+ return;
+ switch (collectionType)
{
- if (collectionType == CollectionType.List)
- {
+ case CollectionType.List:
_storages.Add(name, new ListGenericObjects());
- }
- else if (collectionType == CollectionType.Massive)
- {
+ break;
+ case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects());
- }
+ break;
+ default:
+ break;
}
}
+
///
/// Удаление коллекции
///
@@ -71,15 +76,12 @@ where T : DrawingWarship
///
/// Название коллекции
///
- public ICollectionGenericObjects? this[string name]
+ public ICollectionGenericObjects? this[string name]
{
get
{
- // TODO Продумать логику получения объекта
- if (_storages.ContainsKey(name))
- {
- return _storages[name];
- }
+ if (_storages.TryGetValue(name, out ICollectionGenericObjects? value))
+ return value;
return null;
}
}
@@ -88,16 +90,19 @@ where T : DrawingWarship
///
/// Путь и имя файла
/// 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))
{
File.Delete(filename);
}
+
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
@@ -118,6 +123,7 @@ where T : DrawingWarship
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
+
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
@@ -126,47 +132,43 @@ where T : DrawingWarship
continue;
}
+
streamWriter.Write(data);
streamWriter.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 sr = new StreamReader(filename))// открываем файла на чтение
+
+ using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str != _collectionKey.ToString())
- return false;
-
+ throw new FormatException("В файле неверные данные");
_storages.Clear();
-
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
-
-
if (record.Length != 4)
{
continue;
}
-
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType);
if (collection == null)
{
- return false;
+ throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
@@ -174,25 +176,29 @@ where T : DrawingWarship
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
- if (elem?.CreateDrawingWarship() is T warship)
+ if (elem?.CreateDrawingWarship() is T Warship)
{
- if (collection.Insert(warship) == -1)
- return false;
+ try
+ {
+ if (collection.Insert(Warship) == -1)
+ {
+ throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
+ }
+ }
+ catch (CollectionOverflowException ex)
+ {
+ throw new CollectionOverflowException("Коллекция переполнена", ex);
+ }
}
}
-
_storages.Add(record[0], collection);
}
}
- return true;
}
- private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType)
+ private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) => collectionType switch
{
- return collectionType switch
- {
- CollectionType.Massive => new MassiveGenericObjects(),
- CollectionType.List => new ListGenericObjects(),
- _ => null,
- };
- }
-}
+ CollectionType.Massive => new MassiveGenericObjects(),
+ CollectionType.List => new ListGenericObjects(),
+ _ => null,
+ };
+}
\ No newline at end of file
diff --git a/ProjectBattleship/ProjectBattleship/Exceptions/CollectionOverflowException.cs b/ProjectBattleship/ProjectBattleship/Exceptions/CollectionOverflowException.cs
new file mode 100644
index 0000000..9fcb8be
--- /dev/null
+++ b/ProjectBattleship/ProjectBattleship/Exceptions/CollectionOverflowException.cs
@@ -0,0 +1,17 @@
+using System.Runtime.Serialization;
+namespace ProjectBattleship.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) { }
+}
\ No newline at end of file
diff --git a/ProjectBattleship/ProjectBattleship/Exceptions/ObjectNotFoundException.cs b/ProjectBattleship/ProjectBattleship/Exceptions/ObjectNotFoundException.cs
new file mode 100644
index 0000000..2120135
--- /dev/null
+++ b/ProjectBattleship/ProjectBattleship/Exceptions/ObjectNotFoundException.cs
@@ -0,0 +1,19 @@
+using System.Runtime.Serialization;
+namespace ProjectBattleship.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) { }
+}
\ No newline at end of file
diff --git a/ProjectBattleship/ProjectBattleship/Exceptions/PositionOutOfCollectionException.cs b/ProjectBattleship/ProjectBattleship/Exceptions/PositionOutOfCollectionException.cs
new file mode 100644
index 0000000..243f0ef
--- /dev/null
+++ b/ProjectBattleship/ProjectBattleship/Exceptions/PositionOutOfCollectionException.cs
@@ -0,0 +1,16 @@
+using System.Runtime.Serialization;
+namespace ProjectBattleship.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/ProjectBattleship/ProjectBattleship/FormWarshipCollection.Designer.cs b/ProjectBattleship/ProjectBattleship/FormWarshipCollection.Designer.cs
index 7d455d9..68d4fd7 100644
--- a/ProjectBattleship/ProjectBattleship/FormWarshipCollection.Designer.cs
+++ b/ProjectBattleship/ProjectBattleship/FormWarshipCollection.Designer.cs
@@ -283,7 +283,7 @@ namespace ProjectBattleship
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(278, 34);
saveToolStripMenuItem.Text = "Сохранение ";
- saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
+ saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
diff --git a/ProjectBattleship/ProjectBattleship/FormWarshipCollection.cs b/ProjectBattleship/ProjectBattleship/FormWarshipCollection.cs
index 12430a6..b8a763b 100644
--- a/ProjectBattleship/ProjectBattleship/FormWarshipCollection.cs
+++ b/ProjectBattleship/ProjectBattleship/FormWarshipCollection.cs
@@ -1,4 +1,6 @@
-using ProjectBattleship.CollectionGenericObjects;
+using Battleship.CollectionGenericObjects;
+using Microsoft.Extensions.Logging;
+using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.DrawingObject;
using System.Windows.Forms;
@@ -17,12 +19,17 @@ public partial class FormWarshipCollection : Form
///
private AbstractCompany? _company = null;
///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
+ ///
/// Конструктор
///
- public FormWarshipCollection()
+ public FormWarshipCollection(ILogger logger)
{
InitializeComponent();
_storageCollection = new();
+ _logger = logger;
}
///
/// Выбор компании
@@ -48,21 +55,25 @@ public partial class FormWarshipCollection : Form
///
/// Добавление военного корабля в коллекцию
///
- ///
- private void SetWarship(DrawingWarship? warship)
+ ///
+ private void SetWarship(DrawingWarship warship)
{
if (_company == null || warship == null)
{
return;
}
- if (_company + warship != -1)
+ try
{
+ var res = _company + warship;
MessageBox.Show("Объект добавлен");
+ _logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show();
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не удалось добавить объект");
+ MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
+ MessageBoxIcon.Error);
+ _logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
///
@@ -144,14 +155,18 @@ public partial class FormWarshipCollection : Form
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
- if (_company - pos != null)
+ try
{
+ var res = _company - pos;
MessageBox.Show("Объект удален");
+ _logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox.Image = _company.Show();
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ MessageBox.Show(ex.Message, "Не удалось удалить объект",
+ MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
///
@@ -207,12 +222,12 @@ public partial class FormWarshipCollection : Form
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
- (!radioButtonList.Checked && !radioButtonMassive.Checked))
+ (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
- MessageBox.Show("Не все данные заполнены", "Ошибка",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
+
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
@@ -222,9 +237,19 @@ public partial class FormWarshipCollection : Form
{
collectionType = CollectionType.List;
}
- _storageCollection.AddCollection(textBoxCollectionName.Text,
- collectionType);
- RerfreshListBoxItems();
+
+ try
+ {
+ _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
+ _logger.LogInformation("Добавление коллекции");
+ RerfreshListBoxItems();
+ }
+ catch (Exception ex)
+ {
+ MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError($"Ошибка: {ex.Message}", ex.Message);
+ }
+
}
///
/// Удаление коллекции
@@ -238,16 +263,18 @@ public partial class FormWarshipCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
- if (MessageBox.Show("Вы хотите удалить эту коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
+
+ if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
+ DialogResult.Yes)
{
- string? name = listBoxCollection.SelectedItem.ToString();
- if (!string.IsNullOrEmpty(name))
- {
- _storageCollection.DelCollection(name);
- }
+ return;
}
+
+ _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
+ _logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
+
///
/// Обновление списка в listBoxCollection
///
@@ -295,25 +322,27 @@ public partial class FormWarshipCollection : Form
}
///
- /// Обработка нажатия "Сохранить"
+ /// Обработка нажатия "Сохранение"
///
///
///
- private void saveToolStripMenuItem_Click(object sender, EventArgs e)
+ private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
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);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
-
///
/// Обработка нажатия "Загрузка"
///
@@ -323,14 +352,17 @@ public partial class FormWarshipCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storageCollection.LoadData(openFileDialog.FileName))
+ try
{
- MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems();
+ MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
diff --git a/ProjectBattleship/ProjectBattleship/Program.cs b/ProjectBattleship/ProjectBattleship/Program.cs
index a584329..e324fde 100644
--- a/ProjectBattleship/ProjectBattleship/Program.cs
+++ b/ProjectBattleship/ProjectBattleship/Program.cs
@@ -1,3 +1,11 @@
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using NLog.Extensions.Logging;
+using System.Drawing;
+using System;
+using Microsoft.Extensions.Configuration;
+using Serilog;
+
namespace ProjectBattleship
{
internal static class Program
@@ -8,8 +16,37 @@ namespace ProjectBattleship
[STAThread]
static void Main()
{
- ApplicationConfiguration.Initialize();
- Application.Run(new FormWarshipCollection());
+ // To customize application configuration such as set high DPI settings or default font,
+ // see https://aka.ms/applicationconfiguration.
+ ApplicationConfiguration.Initialize();
+ 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 =>
+ {
+ string[] path = Directory.GetCurrentDirectory().Split('\\');
+ string pathNeed = "";
+ for (int i = 0; i < path.Length - 3; i++)
+ {
+ pathNeed += path[i] + "\\";
+ }
+
+ var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
+ .AddJsonFile(path: $"{pathNeed}serilogConfig.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/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj b/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj
index 13ee123..6ae59a6 100644
--- a/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj
+++ b/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj
@@ -8,6 +8,16 @@
enable
+
+
+
+
+
+
+
+
+
+
True
@@ -23,4 +33,10 @@
+
+
+ Always
+
+
+
\ No newline at end of file
diff --git a/ProjectBattleship/ProjectBattleship/serilogConfig.json b/ProjectBattleship/ProjectBattleship/serilogConfig.json
new file mode 100644
index 0000000..493f426
--- /dev/null
+++ b/ProjectBattleship/ProjectBattleship/serilogConfig.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": "Battleship"
+ }
+ }
+}
\ No newline at end of file