diff --git a/Battleship/Battleship/Battleship.csproj b/Battleship/Battleship/Battleship.csproj
index af03d74..7eb1706 100644
--- a/Battleship/Battleship/Battleship.csproj
+++ b/Battleship/Battleship/Battleship.csproj
@@ -8,6 +8,10 @@
enable
+
+
+
+
True
diff --git a/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs
index b302e2a..64d3622 100644
--- a/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs
+++ b/Battleship/Battleship/CollectionGenericObjects/ListGenericObjects.cs
@@ -1,4 +1,6 @@
-namespace Battleship.CollectionGenericObjects;
+using Battleship.Exception;
+
+namespace Battleship.CollectionGenericObjects;
///
/// Конструктор
@@ -55,7 +57,7 @@ public class ListGenericObjects : ICollectionGenericObjects
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
- if (Count == _maxCount) return -1;
+ if (Count == _maxCount) throw new CollectionOverflowException(_maxCount);
_collection.Add(obj);
return Count;
}
diff --git a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs
index 8fd73ff..3b05b33 100644
--- a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -1,4 +1,6 @@
+using Battleship.Exception;
+
namespace Battleship.CollectionGenericObjects;
///
@@ -12,6 +14,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects
/// Массив объектов, которые храним
///
private T?[] _collection;
+ private int _maxCount;
public int Count => _collection.Length;
@@ -70,7 +73,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects
}
++index;
}
- return -1;
+ throw new CollectionOverflowException(_maxCount);
}
public int Insert(T obj, int position)
diff --git a/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs b/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs
index 61d93ad..38894e9 100644
--- a/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs
+++ b/Battleship/Battleship/CollectionGenericObjects/StorageCollection.cs
@@ -1,5 +1,6 @@
using Battleship.Drawings;
using System.Text;
+using Battleship.Exception;
namespace Battleship.CollectionGenericObjects;
@@ -20,6 +21,11 @@ public class StorageCollection
///
public List Keys => _storages.Keys.ToList();
+ ///
+ /// Ключевое слово, с которого должен начинаться файл
+ ///
+ private readonly string _collectionKey = "CollectionStorage";
+
///
/// Конструктор
///
@@ -36,9 +42,10 @@ public class StorageCollection
public void AddCollection(string name, CollectionType collectionType)
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
- if (_storages.ContainsKey(name))
+ if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
+ {
return;
-
+ }
// TODO Прописать логику для добавления
if (collectionType == CollectionType.List)
{
@@ -80,6 +87,9 @@ public class StorageCollection
}
}
+ ///
+ /// Ключевое слово, с которого должен начинаться файл
+ ///
private readonly string _collectionKey = "CollectionsStorage";
private readonly string _separatorForKeyValue = "|";
@@ -91,11 +101,11 @@ public class StorageCollection
///
///
///
- public bool SaveData(string filname)
+ public void SaveData(string filname)
{
if (_storages.Count == 0)
{
- return false;
+ throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filname))
@@ -117,7 +127,7 @@ public class StorageCollection
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
- continue;
+ throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
sb.Append(value.Key);
@@ -143,19 +153,18 @@ public class StorageCollection
using FileStream fs = new(filname, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
- return true;
}
///
/// Загрузка информации по кораблям в хранилище из файла
///
///
- ///
- public bool LoadData(string filename)
+ ///
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new Exception("Файл не существует");
}
string bufferTextFromFile = "";
@@ -172,12 +181,11 @@ public class StorageCollection
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
- return false;
+ throw new Exception("В файле нет данных");
}
if (!strs[0].Equals(_collectionKey))
{
- //если нет такой записи, то это не те файлы
- return false;
+ throw new Exception("В файле неверные данные");
}
_storages.Clear();
@@ -193,7 +201,7 @@ public class StorageCollection
ICollectionGenericObjects collection = StorageCollection.CreateCollection(collectionType);
if (collection == null)
{
- return false;
+ throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
@@ -202,16 +210,22 @@ public class StorageCollection
{
if (elem?.CreateDrawingWarship() is T warship)
{
- if (collection.Insert(warship) == -1)
+ try
{
- return false;
+ if (collection.Insert(warship) == -1)
+ {
+ throw new Exception("Не удалось создать коллекцию");
+ }
+ }
+ catch (CollectionOverflowException ex)
+ {
+ throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
- return true;
}
private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType)
diff --git a/Battleship/Battleship/Exception/CollectionOverflowException.cs b/Battleship/Battleship/Exception/CollectionOverflowException.cs
new file mode 100644
index 0000000..11d8cd5
--- /dev/null
+++ b/Battleship/Battleship/Exception/CollectionOverflowException.cs
@@ -0,0 +1,20 @@
+using System.Runtime.Serialization;
+
+namespace Battleship.Exception;
+
+///
+/// Класс, описывающий ошибку переполнения коллекции
+///
+[Serializable]
+internal 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 contex) : base(info, contex) { }
+}
diff --git a/Battleship/Battleship/Exception/ObjectNotFoundException.cs b/Battleship/Battleship/Exception/ObjectNotFoundException.cs
new file mode 100644
index 0000000..fcf6819
--- /dev/null
+++ b/Battleship/Battleship/Exception/ObjectNotFoundException.cs
@@ -0,0 +1,19 @@
+using System.Runtime.Serialization;
+
+namespace Battleship.Exception;
+///
+/// Класс, описывающий ошибку, что по указанной позиции нет элемента
+///
+[Serializable]
+internal class ObjectNotFoundException : ApplicationException
+{
+ public ObjectNotFoundException(int count) : base("В коллекции превышено допустимое количество count" + count) { }
+
+ 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/Battleship/Battleship/Exception/PositionOutOfCollectionException.cs b/Battleship/Battleship/Exception/PositionOutOfCollectionException.cs
new file mode 100644
index 0000000..0dae22f
--- /dev/null
+++ b/Battleship/Battleship/Exception/PositionOutOfCollectionException.cs
@@ -0,0 +1,20 @@
+using System.Runtime.Serialization;
+
+namespace Battleship.Exception;
+
+///
+/// Класс, описывающий ошибку выхода за границы коллекции
+///
+[Serializable]
+internal class PositionOutOfCollectionException : ApplicationException
+{
+ public PositionOutOfCollectionException(int count) : base("В коллекции превышено допустимое количество count" + count) { }
+
+ 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/Battleship/Battleship/FormWarshipCollection.cs b/Battleship/Battleship/FormWarshipCollection.cs
index fa18518..444e556 100644
--- a/Battleship/Battleship/FormWarshipCollection.cs
+++ b/Battleship/Battleship/FormWarshipCollection.cs
@@ -1,5 +1,6 @@
using Battleship.CollectionGenericObjects;
using Battleship.Drawings;
+using Microsoft.Extensions.Logging;
using System.Windows.Forms;
namespace Battleship;
@@ -19,13 +20,16 @@ public partial class FormWarshipCollection : Form
///
private AbstractCompany? _company = null;
+ private readonly ILogger _logger;
+
///
/// Конструктор
///
- public FormWarshipCollection()
+ public FormWarshipCollection(ILogger logger)
{
InitializeComponent();
_storageCollection = new();
+ _logger = logger;
}
///
@@ -256,13 +260,16 @@ public partial class FormWarshipCollection : Form
{
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);
}
}
}
diff --git a/Battleship/Battleship/Program.cs b/Battleship/Battleship/Program.cs
index 440f8c8..7fa6b89 100644
--- a/Battleship/Battleship/Program.cs
+++ b/Battleship/Battleship/Program.cs
@@ -1,3 +1,6 @@
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+
namespace Battleship
{
internal static class Program
@@ -11,7 +14,26 @@ namespace Battleship
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
- Application.Run(new FormWarshipCollection());
+ 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 =>
+ {
+ optinon.SetMinimumLevel(LogLevel.Information);
+ option.AddNLog("nlog.config");
+ });
+ }
+
+
}
}
\ No newline at end of file