From 7571290b8b627186cebd9aa1a39df49f632ea1e8 Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Wed, 6 Dec 2023 19:46:10 +0400 Subject: [PATCH 1/5] lab7 --- .../ProjectBattleship/FormShipsCollection.cs | 61 +++++++++++++------ .../ProjectBattleship/Program.cs | 12 +++- .../ProjectBattleship.csproj | 7 +++ .../ProjectBattleship/SetGeneric.cs | 22 +++---- .../ShipNotFoundException.cs | 20 ++++++ .../ShipsGenericCollection.cs | 10 +-- .../ProjectBattleship/ShipsGenericStorage.cs | 16 +++-- .../StorageOverflowException.cs | 19 ++++++ 8 files changed, 120 insertions(+), 47 deletions(-) create mode 100644 ProjectBattleship/ProjectBattleship/ShipNotFoundException.cs create mode 100644 ProjectBattleship/ProjectBattleship/StorageOverflowException.cs 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..c7c9abb 100644 --- a/ProjectBattleship/ProjectBattleship/Program.cs +++ b/ProjectBattleship/ProjectBattleship/Program.cs @@ -1,3 +1,6 @@ +using Serilog; +using Serilog.Events; +using Serilog.Formatting.Json; namespace ProjectBattleship { internal static class Program @@ -8,9 +11,14 @@ 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(); + Log.Logger = new LoggerConfiguration() + .WriteTo.File("log.txt") + .MinimumLevel.Debug() + .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..286c0df 100644 --- a/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj +++ b/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj @@ -8,6 +8,13 @@ enable + + + + + + + True diff --git a/ProjectBattleship/ProjectBattleship/SetGeneric.cs b/ProjectBattleship/ProjectBattleship/SetGeneric.cs index 9ab0502..65bb33d 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..80c7bb5 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) { } + } +} -- 2.25.1 From 21096d1a47c0e8847687d152c4649c2bcdb72d8a Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Wed, 6 Dec 2023 20:50:26 +0400 Subject: [PATCH 2/5] lab7 add config file --- .../ProjectBattleship/Program.cs | 26 ++++++++++++++++--- .../ProjectBattleship.csproj | 13 +++++++++- .../ProjectBattleship/appsettings.json | 15 +++++++++++ 3 files changed, 49 insertions(+), 5 deletions(-) create mode 100644 ProjectBattleship/ProjectBattleship/appsettings.json diff --git a/ProjectBattleship/ProjectBattleship/Program.cs b/ProjectBattleship/ProjectBattleship/Program.cs index c7c9abb..265297a 100644 --- a/ProjectBattleship/ProjectBattleship/Program.cs +++ b/ProjectBattleship/ProjectBattleship/Program.cs @@ -1,6 +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 @@ -11,11 +21,19 @@ namespace ProjectBattleship [STAThread] static void Main() { - ApplicationConfiguration.Initialize(); + 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() - .WriteTo.File("log.txt") - .MinimumLevel.Debug() - .CreateLogger(); + .ReadFrom.Configuration(configuration) + .CreateLogger(); Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); diff --git a/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj b/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj index 286c0df..461699b 100644 --- a/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj +++ b/ProjectBattleship/ProjectBattleship/ProjectBattleship.csproj @@ -9,9 +9,14 @@ - + + + + + + @@ -30,4 +35,10 @@ + + + Always + + + \ No newline at end of file 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 -- 2.25.1 From e4fa3f6fbfd630c03d97e325a3deafcf4180b850 Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Wed, 6 Dec 2023 20:54:21 +0400 Subject: [PATCH 3/5] lab7 some minor fixes --- ProjectBattleship/ProjectBattleship/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ProjectBattleship/ProjectBattleship/Program.cs b/ProjectBattleship/ProjectBattleship/Program.cs index 265297a..aa574bc 100644 --- a/ProjectBattleship/ProjectBattleship/Program.cs +++ b/ProjectBattleship/ProjectBattleship/Program.cs @@ -21,7 +21,8 @@ namespace ProjectBattleship [STAThread] static void Main() { - ApplicationConfiguration.Initialize(); string[] path = Directory.GetCurrentDirectory().Split('\\'); + ApplicationConfiguration.Initialize(); + string[] path = Directory.GetCurrentDirectory().Split('\\'); string pathNeed = ""; for (int i = 0; i < path.Length - 3; i++) { -- 2.25.1 From 2d287aa648c2e2f063f4bace3cebd1d50dc375de Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Fri, 8 Dec 2023 09:09:35 +0400 Subject: [PATCH 4/5] lab7 some minor fixes --- ProjectBattleship/ProjectBattleship/ShipsGenericStorage.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ProjectBattleship/ProjectBattleship/ShipsGenericStorage.cs b/ProjectBattleship/ProjectBattleship/ShipsGenericStorage.cs index 80c7bb5..6e45cf8 100644 --- a/ProjectBattleship/ProjectBattleship/ShipsGenericStorage.cs +++ b/ProjectBattleship/ProjectBattleship/ShipsGenericStorage.cs @@ -61,7 +61,7 @@ namespace ProjectBattleship.Generics } if (data.Length == 0) { - throw new IOException("Невалиданая операция, нет данных для сохранения"); + throw new IOException("Невалидная операция, нет данных для сохранения"); } using (StreamWriter sw = new(filename)) { -- 2.25.1 From abcef124a049ae5c16105c3b4d1443217ae7610b Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Sat, 9 Dec 2023 09:32:40 +0400 Subject: [PATCH 5/5] lab7 preparations for pull request --- ProjectBattleship/ProjectBattleship/SetGeneric.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ProjectBattleship/ProjectBattleship/SetGeneric.cs b/ProjectBattleship/ProjectBattleship/SetGeneric.cs index 65bb33d..779a0b4 100644 --- a/ProjectBattleship/ProjectBattleship/SetGeneric.cs +++ b/ProjectBattleship/ProjectBattleship/SetGeneric.cs @@ -28,7 +28,7 @@ namespace ProjectBattleship.Generics { if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount); - if (!(position >= 0 && position <= Count)) + if (!(position >= 0 && position < Count)) throw new Exception("Неверная позиция для вставки"); _places.Insert(position, ship); } -- 2.25.1