diff --git a/ProjectBattleship/ProjectBattleship/FormShipsCollection.cs b/ProjectBattleship/ProjectBattleship/FormShipsCollection.cs index ac9791f..e56a982 100644 --- a/ProjectBattleship/ProjectBattleship/FormShipsCollection.cs +++ b/ProjectBattleship/ProjectBattleship/FormShipsCollection.cs @@ -1,5 +1,6 @@ using ProjectBattleship.DrawingObjects; using ProjectBattleship.Generics; +using ProjectBattleship.Exceptions; using ProjectBattleship.MovementStrategy; using System; using System.Collections.Generic; @@ -10,6 +11,9 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using System.Xml.Linq; +using Serilog; namespace ProjectBattleship { @@ -65,6 +69,7 @@ namespace ProjectBattleship } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + Log.Information($"Добавлен набор: {textBoxStorageName.Text}"); } /// /// Выбор набора @@ -89,8 +94,10 @@ namespace ProjectBattleship } if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; + _storage.DelSet(name); ReloadObjects(); + Log.Information($"Удален набор: {name}"); } } /// @@ -113,14 +120,17 @@ namespace ProjectBattleship form.Show(); Action shipDelegate = new((ship) => { - if (obj + ship) + try { + bool q = obj + ship; MessageBox.Show("Объект добавлен"); + Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); pictureBoxCollection.Image = obj.ShowShips(); } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена"); + MessageBox.Show(ex.Message); } }); form.AddEvent(shipDelegate); @@ -145,15 +155,23 @@ namespace ProjectBattleship { return; } - int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + var result = obj - pos; MessageBox.Show("Объект удален"); + Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}"); pictureBoxCollection.Image = obj.ShowShips(); } - else + catch (ShipNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); + MessageBox.Show(ex.Message); + } + catch (FormatException) + { + Log.Warning($"Было введено не число"); + MessageBox.Show("Введите число"); } } /// @@ -185,15 +203,16 @@ namespace ProjectBattleship { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен"); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + Log.Warning("Не удалось сохранить"); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -206,19 +225,21 @@ namespace ProjectBattleship { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); Log.Information($"Файл {openFileDialog.FileName} успешно загружен"); + Log.Information($"Файл {openFileDialog.FileName} успешно загружен"); foreach (var collection in _storage.Keys) { listBoxStorages.Items.Add(collection); } + ReloadObjects(); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + Log.Warning("Не удалось загрузить"); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/ProjectBattleship/ProjectBattleship/Program.cs b/ProjectBattleship/ProjectBattleship/Program.cs index b18ddb7..aa574bc 100644 --- a/ProjectBattleship/ProjectBattleship/Program.cs +++ b/ProjectBattleship/ProjectBattleship/Program.cs @@ -1,3 +1,16 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Serilog; +using Serilog.Events; +using Serilog.Formatting.Json; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.IO; + namespace ProjectBattleship { internal static class Program @@ -8,9 +21,23 @@ namespace ProjectBattleship [STAThread] static void Main() { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); + 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}appsettings.json", optional: false, reloadOnChange: true) + .Build(); + Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .CreateLogger(); + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormShipsCollection()); } } diff --git a/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj b/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj index 13ee123..461699b 100644 --- a/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj +++ b/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj @@ -8,6 +8,18 @@ enable + + + + + + + + + + + + True @@ -23,4 +35,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/SetGeneric.cs b/ProjectBattleship/ProjectBattleship/SetGeneric.cs index 9ab0502..779a0b4 100644 --- a/ProjectBattleship/ProjectBattleship/SetGeneric.cs +++ b/ProjectBattleship/ProjectBattleship/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using ProjectBattleship.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -17,26 +18,25 @@ namespace ProjectBattleship.Generics _maxCount = count; _places = new List(count); } - public bool Insert(T ship) + public void Insert(T ship) { if (_places.Count == _maxCount) - return false; + throw new StorageOverflowException(_maxCount); Insert(ship, 0); - return true; } - public bool Insert(T ship, int position) + public void Insert(T ship, int position) { - if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) - return false; + if (_places.Count == _maxCount) + throw new StorageOverflowException(_maxCount); + if (!(position >= 0 && position < Count)) + throw new Exception("Неверная позиция для вставки"); _places.Insert(position, ship); - return true; } - public bool Remove(int position) + public void Remove(int position) { if (!(position >= 0 && position < Count)) - return false; + throw new ShipNotFoundException(position); _places.RemoveAt(position); - return true; } public T? this[int position] { diff --git a/ProjectBattleship/ProjectBattleship/ShipNotFoundException.cs b/ProjectBattleship/ProjectBattleship/ShipNotFoundException.cs new file mode 100644 index 0000000..c0b919d --- /dev/null +++ b/ProjectBattleship/ProjectBattleship/ShipNotFoundException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + + +namespace ProjectBattleship.Exceptions +{ + [Serializable] + internal class ShipNotFoundException : ApplicationException + { + public ShipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public ShipNotFoundException() : base() { } + public ShipNotFoundException(string message) : base(message) { } + public ShipNotFoundException(string message, Exception exception) : base(message, exception) { } + protected ShipNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/ProjectBattleship/ProjectBattleship/ShipsGenericCollection.cs b/ProjectBattleship/ProjectBattleship/ShipsGenericCollection.cs index 19ebdb5..c76fb68 100644 --- a/ProjectBattleship/ProjectBattleship/ShipsGenericCollection.cs +++ b/ProjectBattleship/ProjectBattleship/ShipsGenericCollection.cs @@ -29,16 +29,16 @@ namespace ProjectBattleship.Generics public static bool operator +(ShipsGenericCollection? collect, T? obj) { if (obj != null && collect != null) - return collect._collection.Insert(obj); + { + collect._collection.Insert(obj); + return true; + } return false; } public static T? operator -(ShipsGenericCollection collect, int pos) { T? obj = collect._collection[pos]; - if (obj != null) - { - collect._collection.Remove(pos); - } + collect._collection.Remove(pos); return obj; } public U? GetU(int pos) diff --git a/ProjectBattleship/ProjectBattleship/ShipsGenericStorage.cs b/ProjectBattleship/ProjectBattleship/ShipsGenericStorage.cs index 5b1d15e..6e45cf8 100644 --- a/ProjectBattleship/ProjectBattleship/ShipsGenericStorage.cs +++ b/ProjectBattleship/ProjectBattleship/ShipsGenericStorage.cs @@ -43,7 +43,7 @@ namespace ProjectBattleship.Generics return null; } } - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -61,19 +61,18 @@ namespace ProjectBattleship.Generics } if (data.Length == 0) { - return false; + throw new IOException("Невалидная операция, нет данных для сохранения"); } using (StreamWriter sw = new(filename)) { sw.WriteLine($"ShipStorage{Environment.NewLine}{data}"); } - return true; } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new IOException("Файл не найден"); } using (StreamReader sr = new(filename)) { @@ -81,11 +80,11 @@ namespace ProjectBattleship.Generics var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { - return false; + throw new IOException("Нет данных для загрузки"); } if (!strs[0].StartsWith("ShipStorage")) { - return false; + throw new IOException("Неверный формат данных"); } _shipsStorages.Clear(); do @@ -106,7 +105,7 @@ namespace ProjectBattleship.Generics { if (!(collection + ship)) { - return false; + throw new IOException("Ошибка добавления в коллекцию"); } } } @@ -114,7 +113,6 @@ namespace ProjectBattleship.Generics str = sr.ReadLine(); } while (str != null); } - return true; } } } diff --git a/ProjectBattleship/ProjectBattleship/StorageOverflowException.cs b/ProjectBattleship/ProjectBattleship/StorageOverflowException.cs new file mode 100644 index 0000000..8e66a57 --- /dev/null +++ b/ProjectBattleship/ProjectBattleship/StorageOverflowException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace ProjectBattleship.Exceptions +{ + [Serializable] + internal class StorageOverflowException : ApplicationException + { + public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { } + public StorageOverflowException() : base() { } + public StorageOverflowException(string message) : base(message) { } + public StorageOverflowException(string message, Exception exception) : base(message, exception) { } + protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/ProjectBattleship/ProjectBattleship/appsettings.json b/ProjectBattleship/ProjectBattleship/appsettings.json new file mode 100644 index 0000000..21a6582 --- /dev/null +++ b/ProjectBattleship/ProjectBattleship/appsettings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "log.log" } + } + ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file