diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/AbstractCompany.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/AbstractCompany.cs
index 3b5d2f6..4c47e6e 100644
--- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/AbstractCompany.cs
+++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/AbstractCompany.cs
@@ -32,7 +32,7 @@ public abstract class AbstractCompany
///
/// Вычисление максимального количества элементов, который можно разместить в окне
///
- private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
+ private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
///
/// Конструктор
@@ -54,7 +54,7 @@ public abstract class AbstractCompany
/// Компания
/// Добавляемый объект
///
- public static bool operator +(AbstractCompany company, DrawningTank tank)
+ public static int operator +(AbstractCompany company, DrawningTank tank)
{
return company._collection.Insert(tank);
}
@@ -65,7 +65,7 @@ public abstract class AbstractCompany
/// Компания
/// Номер удаляемого объекта
///
- public static bool operator -(AbstractCompany company, int position)
+ public static DrawningTank operator -(AbstractCompany company, int position)
{
return company._collection.Remove(position);
}
diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ICollectionGenericObjects.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ICollectionGenericObjects.cs
index e25cacb..f96840a 100644
--- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ICollectionGenericObjects.cs
+++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ICollectionGenericObjects.cs
@@ -14,9 +14,9 @@ public interface ICollectionGenericObjects
where T : class
{
///
- /// Количество объектов в коллекции
- ///
- int Count { get; }
+ /// Количество объектов в коллекции
+ ///
+ int Count { get; }
///
/// Установка максимального количества элементов
@@ -28,21 +28,22 @@ public interface ICollectionGenericObjects
///
/// Добавляемый объект
/// true - вставка прошла удачно, false - вставка не удалась
- bool Insert(T obj);
+ int Insert(T obj);
+
///
- /// вставить по позиции
+ /// Добавление объекта в коллекцию на конкретную позицию
///
- /// добавляемый объект
- /// индекс
- ///
- bool Insert(T obj, int position);
+ /// Добавляемый объект
+ /// Позиция
+ /// true - вставка прошла удачно, false - вставка не удалась
+ int Insert(T obj, int position);
///
/// Удаление объекта из коллекции с конкретной позиции
///
/// Позиция
/// true - удаление прошло удачно, false - удаление не удалось
- bool Remove(int position);
+ T? Remove(int position);
///
/// Получение объекта по позиции
@@ -52,13 +53,13 @@ public interface ICollectionGenericObjects
T? Get(int position);
///
- /// Получение типа коллекции
- ///
- CollectionType GetCollectionType { get; }
+ /// Получение типа коллекции (какого типа будет коллекция)
+ ///
+ CollectionType GetCollectionType { get; }
///
- /// Получение объектов коллекции по одному
+ /// Получение объектов(элементов) коллекции по одному
///
- ///
- IEnumerable GetItems();
+ /// Поэлементый вывод элементов коллекции
+ IEnumerable GetItems();
}
diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ListGenericObjects.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ListGenericObjects.cs
index dab3305..84302d2 100644
--- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ListGenericObjects.cs
+++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/ListGenericObjects.cs
@@ -1,4 +1,5 @@
-using System;
+using SelfPropelledArtilleryUnit.Exceptions;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -44,42 +45,38 @@ public class ListGenericObjects : ICollectionGenericObjects
{
_collection = new();
}
-
public T? Get(int position)
{
- if (position < 0 || position >= _collection.Count || _collection == null || _collection.Count == 0) return null;
-
+ if (position < 0 || position >= Count) return null;
return _collection[position];
}
- public bool Insert(T obj)
+ public int Insert(T? obj)
{
- if (_collection == null || _collection.Count == _maxCount) return false;
-
+ if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
- return true;
+ return Count - 1;
}
- public bool Insert(T obj, int position)
+ public int Insert(T? obj, int position)
{
- if (_collection == null || position < 0 || position > _maxCount) return false;
-
+ if (Count == _maxCount) throw new CollectionOverflowException(Count);
+ if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
- return true;
+ return position;
}
- public bool Remove(int position)
+ public T? Remove(int position)
{
- if (_collection == null || position < 0 || position >= _collection.Count) return false;
-
+ if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
T? obj = _collection[position];
- _collection[position] = null;
- return true;
+ _collection.RemoveAt(position);
+ return obj;
}
- public IEnumerable GetItems()
+ public IEnumerable GetItems()
{
- for (int i = 0; i < _collection.Count; i++)
+ for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/MassiveGenericObjects.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/MassiveGenericObjects.cs
index 0de4dcf..3868250 100644
--- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -1,4 +1,5 @@
-using System;
+using SelfPropelledArtilleryUnit.Exceptions;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -9,36 +10,32 @@ namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
public class MassiveGenericObjects : ICollectionGenericObjects
where T : class
{
- ///
- /// Массив объектов, которые храним
- ///
private T?[] _collection;
-
- public int Count { get { return _collection.Length; } }
-
+ public int Count => _collection.Length;
public int MaxCount
{
get
{
return _collection.Length;
}
-
set
{
- if (value > 0 && _collection.Length == 0)
+ if (value > 0)
{
- _collection = new T?[value];
+ if (_collection.Length > 0)
+ {
+ Array.Resize(ref _collection, value);
+ }
+ else
+ {
+ _collection = new T?[value];
+ }
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
- public int SetMaxCount { set => throw new NotImplementedException(); }
-
- ///
- /// Конструктор
- ///
public MassiveGenericObjects()
{
_collection = Array.Empty();
@@ -47,31 +44,31 @@ public class MassiveGenericObjects : ICollectionGenericObjects
public T? Get(int position)
{
if (position < 0 || position >= _collection.Length)
+ {
return null;
+ }
return _collection[position];
}
-
- public bool Insert(T obj)
+ public int Insert(T obj)
{
for (int i = 0; i < _collection.Length; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
- return true;
+ return i;
}
}
- return false;
+ throw new CollectionOverflowException(Count); ;
}
-
- public bool Insert(T obj, int position)
+ public int Insert(T obj, int position)
{
- if (position < 0 || position >= _collection.Length) { return false; }
+ if (position < 0 || position >= _collection.Length) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
_collection[position] = obj;
- return true;
+ return position;
}
else
{
@@ -80,7 +77,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects
if (_collection[i] == null)
{
_collection[i] = obj;
- return true;
+ return i;
}
}
@@ -89,29 +86,31 @@ public class MassiveGenericObjects : ICollectionGenericObjects
if (_collection[i] == null)
{
_collection[i] = obj;
- return true;
+ return i;
}
}
}
- return false;
+ throw new CollectionOverflowException(Count);
}
-
- public bool Remove(int position)
+ public T Remove(int position)
{
- if (position < 0 || position >= _collection.Length) { return false; }
+ if (position < 0 || position >= _collection.Length)
+ {
+ throw new PositionOutOfCollectionException(position);
+ }
+ if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? obj = _collection[position];
_collection[position] = null;
- return true;
+
+ return obj;
}
- public IEnumerable GetItems()
+ public IEnumerable GetItems()
{
for (int i = 0; i < _collection.Length; i++)
{
yield return _collection[i];
}
}
-
-
-}
+}
\ No newline at end of file
diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/StorageCollection.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/StorageCollection.cs
index 7cd1557..f5abca9 100644
--- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/StorageCollection.cs
+++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/StorageCollection.cs
@@ -1,4 +1,5 @@
using SelfPropelledArtilleryUnit.Drawnings;
+using SelfPropelledArtilleryUnit.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -81,11 +82,12 @@ public class StorageCollection
return null;
}
}
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (_storages.Count == 0)
{
- return false;
+ throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
+
}
if (File.Exists(filename))
{
@@ -121,26 +123,25 @@ public class StorageCollection
}
writer.Write(sb);
}
- return true;
}
}
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new FileNotFoundException("Файл не существует");
}
using (StreamReader reader = File.OpenText(filename))
{
string str = reader.ReadLine();
if (str == null || str.Length == 0)
{
- return false;
+ throw new InvalidOperationException("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
- return false;
+ throw new InvalidOperationException("В файле не верные данные");
}
_storages.Clear();
string strs = "";
@@ -155,7 +156,7 @@ public class StorageCollection
ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType);
if (collection == null)
{
- return false;
+ throw new InvalidOperationException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries);
@@ -163,15 +164,21 @@ public class StorageCollection
{
if (elem?.CreateDrawningTank() is T tank)
{
- if (!collection.Insert(tank))
+ try
{
- return false;
+ if (collection.Insert(tank)==-1)
+ {
+ throw new InvalidOperationException("Объект не удалось добавить в коллекцию " + record[3]);
+ }
+ }
+ catch (CollectionOverflowException ex)
+ {
+ throw new InvalidOperationException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
- return true;
}
}
private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType)
diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/TankSharingService.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/TankSharingService.cs
index f81a2a9..34a3c78 100644
--- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/TankSharingService.cs
+++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/CollectionGenericObjects/TankSharingService.cs
@@ -36,28 +36,28 @@ public class TankSharingService : AbstractCompany
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
- int tankWidth = 0;
- int tankHeight = height - 1;
+ int locomotiveWidth = 0;
+ int locomotiveHeight = height - 1;
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection.Get(i) != null)
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
- _collection.Get(i).SetPosition(_placeSizeWidth * tankWidth + 20, tankHeight * _placeSizeHeight + 20);
+ _collection.Get(i).SetPosition(_placeSizeWidth * locomotiveWidth + 20, locomotiveHeight * _placeSizeHeight + 20);
}
- if (tankWidth < width - 1)
- tankWidth++;
+ if (locomotiveWidth < width - 1)
+ locomotiveWidth++;
else
{
- tankWidth = 0;
- tankHeight--;
+ locomotiveWidth = 0;
+ locomotiveHeight--;
}
- if (tankHeight < 0)
+ if (locomotiveHeight < 0)
{
return;
}
}
}
-}
+}
\ No newline at end of file
diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Exceptions/CollectionOverflowException.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Exceptions/CollectionOverflowException.cs
new file mode 100644
index 0000000..08aa112
--- /dev/null
+++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Exceptions/CollectionOverflowException.cs
@@ -0,0 +1,21 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Runtime.Serialization;
+namespace SelfPropelledArtilleryUnit.Exceptions;
+
+[Serializable]
+public class CollectionOverflowException : ApplicationException
+{
+ public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество count : " + count) { }
+
+ public CollectionOverflowException() : base() { }
+
+ public CollectionOverflowException(string message) : base(message) { }
+
+ public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
+
+ protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+}
diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Exceptions/ObjectNotFoundException.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Exceptions/ObjectNotFoundException.cs
new file mode 100644
index 0000000..47b9c9f
--- /dev/null
+++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Exceptions/ObjectNotFoundException.cs
@@ -0,0 +1,23 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SelfPropelledArtilleryUnit.Exceptions;
+
+[Serializable]
+public 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 context) : base(info, context) { }
+}
+
diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Exceptions/PozitionOutOfCollectionException.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Exceptions/PozitionOutOfCollectionException.cs
new file mode 100644
index 0000000..6a3cd87
--- /dev/null
+++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Exceptions/PozitionOutOfCollectionException.cs
@@ -0,0 +1,21 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SelfPropelledArtilleryUnit.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/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormTankCollection.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormTankCollection.cs
index b5473bb..178b1d8 100644
--- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormTankCollection.cs
+++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormTankCollection.cs
@@ -1,7 +1,8 @@
-
-
+using Microsoft.Extensions.Logging;
+using NLog;
using SelfPropelledArtilleryUnit.CollectionGenericObjects;
using SelfPropelledArtilleryUnit.Drawnings;
+using SelfPropelledArtilleryUnit.Exceptions;
namespace SelfPropelledArtilleryUnit;
@@ -12,14 +13,15 @@ public partial class FormTankCollection : Form
///
private AbstractCompany? _company = null;
private readonly StorageCollection _storageCollection;
-
+ private readonly Microsoft.Extensions.Logging.ILogger _logger;
///
/// Конструктор
///
- public FormTankCollection()
+ public FormTankCollection(ILogger logger)
{
InitializeComponent();
_storageCollection = new();
+ _logger = logger;
}
///
/// Выбор компании
@@ -46,20 +48,25 @@ public partial class FormTankCollection : Form
///
private void SetTank(DrawningTank? tank)
{
+ try {
if (_company == null || tank == null)
{
return;
}
- if (_company + tank)
+ if (_company + tank != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
+ _logger.LogInformation("Добавлен объект: " + tank.GetDataForSave());
+ }
}
- else
+ catch (CollectionOverflowException ex)
{
- MessageBox.Show("Не удалось добавить объект");
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
+
}
///
@@ -80,16 +87,25 @@ public partial class FormTankCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
-
- if (_company - pos != null)
+ try
{
- MessageBox.Show("Объект удален");
- pictureBox.Image = _company.Show();
+ if (_company - pos != null)
+ {
+ MessageBox.Show("Объект удален");
+ _logger.LogInformation($"Удален объект по позиции {pos}");
+ pictureBox.Image = _company.Show();
+ }
}
- else
+ catch (ObjectNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ MessageBox.Show(ex.Message);
+ _logger.LogError($"Ошибка: {ex.Message}");
+ }
+ catch (PositionOutOfCollectionException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogError($"Ошибка: {ex.Message}");
}
}
@@ -140,21 +156,30 @@ public partial class FormTankCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: заполнены не все данные для добавления коллекции");
return;
}
-
- CollectionType collectionType = CollectionType.None;
- if (radioButtonMassive.Checked)
+ try
{
- collectionType = CollectionType.Massive;
- }
- else if (radioButtonList.Checked)
- {
- collectionType = CollectionType.List;
- }
- _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
- RerfreshListBoxItems();
+ 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);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
}
private void RerfreshListBoxItems()
{
@@ -176,12 +201,20 @@ public partial class FormTankCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
- if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
+ try
{
- return;
+ if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
+ {
+ return;
+ }
+ _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
+ RerfreshListBoxItems();
+ _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
- _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
- RerfreshListBoxItems();
}
private void ButtonCreateCompany_Click(object sender, EventArgs e)
@@ -229,15 +262,16 @@ public partial class FormTankCollection : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storageCollection.SaveData(saveFileDialog.FileName))
+ try
{
- MessageBox.Show("Сохранение прошло успешно", "Резудьтат",
- MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _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);
}
}
}
@@ -246,19 +280,18 @@ public partial class FormTankCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storageCollection.LoadData(openFileDialog.FileName))
+ try
{
- MessageBox.Show("Загрузка прошла успешно", "Результат",
- MessageBoxButtons.OK, MessageBoxIcon.Information);
- RefreshListBoxItems();
+ _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("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
}
-
-
diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs
index 25a66f7..d0aab71 100644
--- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs
+++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs
@@ -1,3 +1,8 @@
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using System;
+using NLog.Extensions.Logging;
+
namespace SelfPropelledArtilleryUnit
{
internal static class Program
@@ -10,8 +15,21 @@ namespace SelfPropelledArtilleryUnit
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
+ ServiceCollection services = new();
+ ConfigureServices(services);
ApplicationConfiguration.Initialize();
- Application.Run(new FormTankCollection());
+ ConfigureServices(services);
+ using ServiceProvider serviceProvider = services.BuildServiceProvider();
+ Application.Run(serviceProvider.GetRequiredService());
+ }
+ private static void ConfigureServices(ServiceCollection services)
+ {
+ services.AddSingleton()
+ .AddLogging(option =>
+ {
+ option.SetMinimumLevel(LogLevel.Information);
+ option.AddNLog("nlog.config");
+ });
}
}
}
\ No newline at end of file
diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj
index af03d74..2f60d77 100644
--- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj
+++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj
@@ -8,6 +8,13 @@
enable
+
+
+
+
+
+
+
True
@@ -23,4 +30,10 @@
+
+
+ Always
+
+
+
\ No newline at end of file
diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/nlog.config b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/nlog.config
new file mode 100644
index 0000000..9826983
--- /dev/null
+++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/nlog.config
@@ -0,0 +1,14 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file