From 33b1fe2e2bfe11106e27ad52639d58ff231aab7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=BE=D1=84=D1=8C=D1=8F=20=D0=AF=D0=BA=D0=BE=D0=B1?= =?UTF-8?q?=D1=87=D1=83=D0=BA?= Date: Tue, 12 Dec 2023 12:38:44 +0400 Subject: [PATCH 1/4] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=BC=D0=B5=D0=B6=D1=83?= =?UTF-8?q?=D1=82=D0=BE=D1=87=D0=BD=D0=B0=D1=8F=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sailboat/Sailboat/BoatNotFoundException.cs | 17 +++++++ Sailboat/Sailboat/BoatsGenericStorage.cs | 13 +++--- .../Sailboat/FormBoatCollection.Designer.cs | 6 +-- Sailboat/Sailboat/FormBoatCollection.cs | 46 +++++++++++++------ Sailboat/Sailboat/StorageOverflowException.cs | 16 +++++++ 5 files changed, 73 insertions(+), 25 deletions(-) create mode 100644 Sailboat/Sailboat/BoatNotFoundException.cs create mode 100644 Sailboat/Sailboat/StorageOverflowException.cs diff --git a/Sailboat/Sailboat/BoatNotFoundException.cs b/Sailboat/Sailboat/BoatNotFoundException.cs new file mode 100644 index 0000000..79aa34c --- /dev/null +++ b/Sailboat/Sailboat/BoatNotFoundException.cs @@ -0,0 +1,17 @@ +using System.Runtime.Serialization; + +namespace Sailboat.Exceptions +{ + [Serializable] + internal class BoatNotFoundException : ApplicationException + { + public BoatNotFoundException(int i) : base($"Не найден объект по позиции { i}") { } + public BoatNotFoundException() : base() { } + public BoatNotFoundException(string message) : base(message) { } + public BoatNotFoundException(string message, Exception exception) : + base(message, exception) + { } + protected BoatNotFoundException(SerializationInfo info, + StreamingContext contex) : base(info, contex) { } + } +} \ No newline at end of file diff --git a/Sailboat/Sailboat/BoatsGenericStorage.cs b/Sailboat/Sailboat/BoatsGenericStorage.cs index a1f376b..7108ca1 100644 --- a/Sailboat/Sailboat/BoatsGenericStorage.cs +++ b/Sailboat/Sailboat/BoatsGenericStorage.cs @@ -97,7 +97,6 @@ namespace Sailboat.Generics /// Сохранение информации по лодкам в хранилище в файл /// /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных public bool SaveData(string filename) { if (File.Exists(filename)) @@ -116,11 +115,11 @@ namespace Sailboat.Generics } if (data.Length == 0) { - return false; + throw new Exception("Невалиданя операция, нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) { - writer.Write($"BoatStorage{Environment.NewLine}{data}"); + writer.Write($"PlaneStorage{Environment.NewLine}{data}"); } return true; } @@ -133,7 +132,7 @@ namespace Sailboat.Generics { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } using (StreamReader fs = File.OpenText(filename)) @@ -141,11 +140,11 @@ namespace Sailboat.Generics string str = fs.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new Exception("Нет данных для загрузки"); } if (!str.StartsWith("BoatStorage")) { - return false; + throw new Exception("Неверный формат данных"); } _boatStorages.Clear(); @@ -172,7 +171,7 @@ namespace Sailboat.Generics { if (!(collection + boat)) { - return false; + throw new Exception("Ошибка добавления в коллекцию"); } } } diff --git a/Sailboat/Sailboat/FormBoatCollection.Designer.cs b/Sailboat/Sailboat/FormBoatCollection.Designer.cs index 0de397b..7968f58 100644 --- a/Sailboat/Sailboat/FormBoatCollection.Designer.cs +++ b/Sailboat/Sailboat/FormBoatCollection.Designer.cs @@ -182,24 +182,24 @@ // SaveToolStripMenuItem // SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; - SaveToolStripMenuItem.Size = new Size(177, 26); + SaveToolStripMenuItem.Size = new Size(224, 26); SaveToolStripMenuItem.Text = "Сохранение"; SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; // // LoadToolStripMenuItem // LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; - LoadToolStripMenuItem.Size = new Size(177, 26); + LoadToolStripMenuItem.Size = new Size(224, 26); LoadToolStripMenuItem.Text = "Загрузка"; LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; // // openFileDialog // + openFileDialog.FileName = "openFileDialog"; openFileDialog.Filter = "txt file | *.txt"; // // saveFileDialog // - saveFileDialog.FileName = "BoatSave"; saveFileDialog.Filter = "txt file | *.txt"; // // FormBoatCollection diff --git a/Sailboat/Sailboat/FormBoatCollection.cs b/Sailboat/Sailboat/FormBoatCollection.cs index ad3b6a0..b5f3d00 100644 --- a/Sailboat/Sailboat/FormBoatCollection.cs +++ b/Sailboat/Sailboat/FormBoatCollection.cs @@ -9,6 +9,7 @@ using System.Threading.Tasks; using System.Windows.Forms; using Sailboat.DrawingObjects; +using Sailboat.Exceptions; using Sailboat.Generics; using Sailboat.MovementStrategy; @@ -91,14 +92,21 @@ namespace Sailboat return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowBoats(); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowBoats(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (BoatNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); } } @@ -153,15 +161,16 @@ namespace Sailboat { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -170,18 +179,25 @@ namespace Sailboat { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + 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); + } } - ReloadObjects(); } } -} +} \ No newline at end of file diff --git a/Sailboat/Sailboat/StorageOverflowException.cs b/Sailboat/Sailboat/StorageOverflowException.cs new file mode 100644 index 0000000..00e7a03 --- /dev/null +++ b/Sailboat/Sailboat/StorageOverflowException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace Sailboat.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 contex) : base(info, contex) { } + } +} \ No newline at end of file -- 2.25.1 From b51f1183fc6e9017a348d536371fdf37c53beba9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=BE=D1=84=D1=8C=D1=8F=20=D0=AF=D0=BA=D0=BE=D0=B1?= =?UTF-8?q?=D1=87=D1=83=D0=BA?= Date: Tue, 12 Dec 2023 14:30:43 +0400 Subject: [PATCH 2/4] =?UTF-8?q?=D0=A1=D0=BE=D1=85=D1=80=D0=B0=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=81=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BA?= =?UTF-8?q?=D0=B0=D0=BC=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sailboat/Sailboat/BoatNotFoundException.cs | 7 +++++- Sailboat/Sailboat/BoatsGenericCollection.cs | 7 ++---- Sailboat/Sailboat/BoatsGenericStorage.cs | 4 +-- Sailboat/Sailboat/DrawingBoat.cs | 3 +++ Sailboat/Sailboat/ExtentionDrawingBoat.cs | 2 ++ Sailboat/Sailboat/FormBoatCollection.cs | 16 +++++++++--- Sailboat/Sailboat/Program.cs | 25 ++++++++++++++++++- Sailboat/Sailboat/Sailboat.csproj | 7 ++++++ Sailboat/Sailboat/SetGeneric.cs | 10 +++++--- Sailboat/Sailboat/StorageOverflowException.cs | 7 +++++- Sailboat/Sailboat/debug.json | 15 +++++++++++ 11 files changed, 86 insertions(+), 17 deletions(-) create mode 100644 Sailboat/Sailboat/debug.json diff --git a/Sailboat/Sailboat/BoatNotFoundException.cs b/Sailboat/Sailboat/BoatNotFoundException.cs index 79aa34c..77f4ab0 100644 --- a/Sailboat/Sailboat/BoatNotFoundException.cs +++ b/Sailboat/Sailboat/BoatNotFoundException.cs @@ -1,4 +1,9 @@ -using System.Runtime.Serialization; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; namespace Sailboat.Exceptions { diff --git a/Sailboat/Sailboat/BoatsGenericCollection.cs b/Sailboat/Sailboat/BoatsGenericCollection.cs index d167081..61d317c 100644 --- a/Sailboat/Sailboat/BoatsGenericCollection.cs +++ b/Sailboat/Sailboat/BoatsGenericCollection.cs @@ -77,13 +77,10 @@ namespace Sailboat.Generics public static bool operator -(BoatsGenericCollection collect, int pos) { T? obj = collect._collection[pos]; - if (obj != null) - { - collect._collection.Remove(pos); - } + collect._collection.Remove(pos); return false; } - + /// /// Получение объекта IMoveableObject /// diff --git a/Sailboat/Sailboat/BoatsGenericStorage.cs b/Sailboat/Sailboat/BoatsGenericStorage.cs index 7108ca1..1c0d52d 100644 --- a/Sailboat/Sailboat/BoatsGenericStorage.cs +++ b/Sailboat/Sailboat/BoatsGenericStorage.cs @@ -115,11 +115,11 @@ namespace Sailboat.Generics } if (data.Length == 0) { - throw new Exception("Невалиданя операция, нет данных для сохранения"); + throw new Exception("Невалидная операция, нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) { - writer.Write($"PlaneStorage{Environment.NewLine}{data}"); + writer.Write($"SailboatStorage{Environment.NewLine}{data}"); } return true; } diff --git a/Sailboat/Sailboat/DrawingBoat.cs b/Sailboat/Sailboat/DrawingBoat.cs index a476002..f36f5f6 100644 --- a/Sailboat/Sailboat/DrawingBoat.cs +++ b/Sailboat/Sailboat/DrawingBoat.cs @@ -22,6 +22,9 @@ namespace Sailboat.DrawingObjects private readonly int _boatWidth = 185; private readonly int _boatHeight = 160; public int GetPosX => _startPosX; + + char separator = '|'; + public int GetPosY => _startPosY; public int GetWidth => _boatWidth; public int GetHeight => _boatHeight; diff --git a/Sailboat/Sailboat/ExtentionDrawingBoat.cs b/Sailboat/Sailboat/ExtentionDrawingBoat.cs index d23753c..aee9338 100644 --- a/Sailboat/Sailboat/ExtentionDrawingBoat.cs +++ b/Sailboat/Sailboat/ExtentionDrawingBoat.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; +using Microsoft.VisualBasic.Logging; using Sailboat.Entities; namespace Sailboat.DrawingObjects diff --git a/Sailboat/Sailboat/FormBoatCollection.cs b/Sailboat/Sailboat/FormBoatCollection.cs index b5f3d00..0e7f5fa 100644 --- a/Sailboat/Sailboat/FormBoatCollection.cs +++ b/Sailboat/Sailboat/FormBoatCollection.cs @@ -1,12 +1,16 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; +using System.Diagnostics.Metrics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using System.Xml.Linq; +using Serilog; using Sailboat.DrawingObjects; using Sailboat.Exceptions; @@ -18,10 +22,12 @@ namespace Sailboat public partial class FormBoatCollection : Form { private readonly BoatsGenericStorage _storage; + private readonly ILogger _logger; public FormBoatCollection() { InitializeComponent(); _storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } private void ReloadObjects() @@ -135,6 +141,7 @@ namespace Sailboat } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}"); } private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e) @@ -149,11 +156,12 @@ namespace Sailboat { return; } + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() - ?? string.Empty); - ReloadObjects(); + _storage.DelSet(name); + ReloadObjects(); ; + _logger.LogInformation($"Удален набор: {name}"); } } diff --git a/Sailboat/Sailboat/Program.cs b/Sailboat/Sailboat/Program.cs index fac24ad..c1bdb59 100644 --- a/Sailboat/Sailboat/Program.cs +++ b/Sailboat/Sailboat/Program.cs @@ -1,3 +1,11 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.Events; +using Serilog.Formatting.Json; +using Serilog.Configuration; + namespace Sailboat { internal static class Program @@ -10,7 +18,22 @@ namespace Sailboat { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. - 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}debug.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 FormBoatCollection()); } } diff --git a/Sailboat/Sailboat/Sailboat.csproj b/Sailboat/Sailboat/Sailboat.csproj index 13ee123..b2c4814 100644 --- a/Sailboat/Sailboat/Sailboat.csproj +++ b/Sailboat/Sailboat/Sailboat.csproj @@ -8,6 +8,13 @@ enable + + + + + + + True diff --git a/Sailboat/Sailboat/SetGeneric.cs b/Sailboat/Sailboat/SetGeneric.cs index db44393..b3d3f93 100644 --- a/Sailboat/Sailboat/SetGeneric.cs +++ b/Sailboat/Sailboat/SetGeneric.cs @@ -1,8 +1,10 @@ using System; +using Sailboat.Exceptions; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Windows.Forms; namespace Sailboat.Generics { @@ -38,7 +40,7 @@ namespace Sailboat.Generics { if (_places.Count == _maxCount) { - return false; + throw new StorageOverflowException(_maxCount); } Insert(boat, 0); return true; @@ -51,7 +53,9 @@ namespace Sailboat.Generics /// public bool Insert(T boat, int position) { - if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) + if (_places.Count == _maxCount) + throw new StorageOverflowException(_maxCount); + if (!(position >= 0 && position <= Count)) { return false; } @@ -67,7 +71,7 @@ namespace Sailboat.Generics { if (position < 0 || position >= Count) { - return false; + throw new BoatNotFoundException(position); } _places.RemoveAt(position); return true; diff --git a/Sailboat/Sailboat/StorageOverflowException.cs b/Sailboat/Sailboat/StorageOverflowException.cs index 00e7a03..15de1fe 100644 --- a/Sailboat/Sailboat/StorageOverflowException.cs +++ b/Sailboat/Sailboat/StorageOverflowException.cs @@ -1,4 +1,9 @@ -using System.Runtime.Serialization; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; namespace Sailboat.Exceptions { diff --git a/Sailboat/Sailboat/debug.json b/Sailboat/Sailboat/debug.json new file mode 100644 index 0000000..812a97c --- /dev/null +++ b/Sailboat/Sailboat/debug.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "log.txt" } + } + ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file -- 2.25.1 From 3331db9236250cc797bae1cb158bb17eb5955914 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=BE=D1=84=D1=8C=D1=8F=20=D0=AF=D0=BA=D0=BE=D0=B1?= =?UTF-8?q?=D1=87=D1=83=D0=BA?= Date: Sun, 24 Dec 2023 22:26:50 +0400 Subject: [PATCH 3/4] =?UTF-8?q?=D0=9E=D1=88=D0=B8=D0=B1=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=B2=20Program?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sailboat/Sailboat/BoatNotFoundException.cs | 11 +- Sailboat/Sailboat/BoatsGenericCollection.cs | 11 +- Sailboat/Sailboat/BoatsGenericStorage.cs | 80 +++++++------- Sailboat/Sailboat/DrawingBoat.cs | 4 +- Sailboat/Sailboat/FormBoatCollection.cs | 100 ++++++++++-------- Sailboat/Sailboat/FormBoatConfig.cs | 22 ++-- Sailboat/Sailboat/Program.cs | 43 ++++---- Sailboat/Sailboat/Sailboat.csproj | 56 +++++----- Sailboat/Sailboat/StorageOverflowException.cs | 4 +- Sailboat/Sailboat/appSetting.json | 20 ++++ Sailboat/Sailboat/debug.json | 15 --- 11 files changed, 194 insertions(+), 172 deletions(-) create mode 100644 Sailboat/Sailboat/appSetting.json delete mode 100644 Sailboat/Sailboat/debug.json diff --git a/Sailboat/Sailboat/BoatNotFoundException.cs b/Sailboat/Sailboat/BoatNotFoundException.cs index 77f4ab0..27c20d5 100644 --- a/Sailboat/Sailboat/BoatNotFoundException.cs +++ b/Sailboat/Sailboat/BoatNotFoundException.cs @@ -1,22 +1,19 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; -using System.Runtime.Serialization; namespace Sailboat.Exceptions { [Serializable] internal class BoatNotFoundException : ApplicationException { - public BoatNotFoundException(int i) : base($"Не найден объект по позиции { i}") { } + public BoatNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } public BoatNotFoundException() : base() { } public BoatNotFoundException(string message) : base(message) { } - public BoatNotFoundException(string message, Exception exception) : - base(message, exception) - { } - protected BoatNotFoundException(SerializationInfo info, - StreamingContext contex) : base(info, contex) { } + public BoatNotFoundException(string message, Exception exception) : base(message, exception) { } + protected BoatNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } } } \ No newline at end of file diff --git a/Sailboat/Sailboat/BoatsGenericCollection.cs b/Sailboat/Sailboat/BoatsGenericCollection.cs index 61d317c..27b85bf 100644 --- a/Sailboat/Sailboat/BoatsGenericCollection.cs +++ b/Sailboat/Sailboat/BoatsGenericCollection.cs @@ -37,9 +37,6 @@ namespace Sailboat.Generics /// Набор объектов /// private readonly SetGeneric _collection; - /// - /// Получение объектов коллекции - /// public IEnumerable GetBoats => _collection.GetBoats(); /// /// Конструктор @@ -74,13 +71,13 @@ namespace Sailboat.Generics /// /// /// - public static bool operator -(BoatsGenericCollection collect, int pos) + public static T? operator -(BoatsGenericCollection collect, int pos) { T? obj = collect._collection[pos]; collect._collection.Remove(pos); - return false; + return obj; } - + /// /// Получение объекта IMoveableObject /// @@ -134,6 +131,8 @@ namespace Sailboat.Generics if (boat != null) { int width = _pictureWidth / _placeSizeWidth; + boat._pictureWidth = _pictureWidth; + boat._pictureHeight = _pictureHeight; boat.SetPosition(i % width * _placeSizeWidth, i / width * _placeSizeHeight); boat.DrawTransport(g); } diff --git a/Sailboat/Sailboat/BoatsGenericStorage.cs b/Sailboat/Sailboat/BoatsGenericStorage.cs index 1c0d52d..c9390b5 100644 --- a/Sailboat/Sailboat/BoatsGenericStorage.cs +++ b/Sailboat/Sailboat/BoatsGenericStorage.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using Sailboat.DrawingObjects; using Sailboat.MovementStrategy; +using Sailboat.Exceptions; namespace Sailboat.Generics { @@ -46,8 +47,7 @@ namespace Sailboat.Generics /// public BoatsGenericStorage(int pictureWidth, int pictureHeight) { - _boatStorages = new Dictionary>(); + _boatStorages = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } @@ -80,8 +80,7 @@ namespace Sailboat.Generics /// /// /// - public BoatsGenericCollection? - this[string ind] + public BoatsGenericCollection? this[string ind] { get { @@ -97,12 +96,14 @@ namespace Sailboat.Generics /// Сохранение информации по лодкам в хранилище в файл /// /// Путь и имя файла - public bool SaveData(string filename) + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public void SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } + StringBuilder data = new(); foreach (KeyValuePair> record in _boatStorages) { @@ -112,72 +113,75 @@ namespace Sailboat.Generics records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); } data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + } if (data.Length == 0) { - throw new Exception("Невалидная операция, нет данных для сохранения"); + throw new InvalidOperationException("Файл не найден, невалидная операция, нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) { - writer.Write($"SailboatStorage{Environment.NewLine}{data}"); + writer.WriteLine("BoatStorage"); + writer.Write(data.ToString()); } - return true; } + /// /// Загрузка информации по лодкам в хранилище из файла /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка призагрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - throw new Exception("Файл не найден"); + throw new FileNotFoundException("Файл не найден"); } - using (StreamReader fs = File.OpenText(filename)) + using (StreamReader reader = new StreamReader(filename)) { - string str = fs.ReadLine(); - if (str == null || str.Length == 0) + string checker = reader.ReadLine(); + if (checker == null) + throw new NullReferenceException("Нет данных для загрузки"); + if (!checker.StartsWith("BoatStorage")) { - throw new Exception("Нет данных для загрузки"); - } - if (!str.StartsWith("BoatStorage")) - { - throw new Exception("Неверный формат данных"); + //если нет такой записи, то это не те данные + throw new FormatException("Неверный формат данных"); } _boatStorages.Clear(); - string strs = ""; - - while ((strs = fs.ReadLine()) != null) + string strs; + bool firstinit = true; + while ((strs = reader.ReadLine()) != null) { + if (strs == null && firstinit) + throw new NullReferenceException("Нет данных для загрузки"); if (strs == null) - { - return false; - } - - string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 2) - { - continue; - } + break; + firstinit = false; + string name = strs.Split('|')[0]; BoatsGenericCollection collection = new(_pictureWidth, _pictureHeight); - string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) + foreach (string data in strs.Split('|')[1].Split(';')) { - DrawingBoat? boat = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight); - if (boat != null) + DrawingBoat? vehicle = data?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight); + if (vehicle != null) { - if (!(collection + boat)) + try { - throw new Exception("Ошибка добавления в коллекцию"); + _ = collection + vehicle; + } + catch (BoatNotFoundException e) + { + throw e; + } + catch (StorageOverflowException e) + { + throw e; } } } - _boatStorages.Add(record[0], collection); + _boatStorages.Add(name, collection); } - return true; } } } diff --git a/Sailboat/Sailboat/DrawingBoat.cs b/Sailboat/Sailboat/DrawingBoat.cs index f36f5f6..ff31d25 100644 --- a/Sailboat/Sailboat/DrawingBoat.cs +++ b/Sailboat/Sailboat/DrawingBoat.cs @@ -15,8 +15,8 @@ namespace Sailboat.DrawingObjects public class DrawingBoat { public EntityBoat? EntityBoat { get; protected set; } - private int _pictureWidth; - private int _pictureHeight; + public int _pictureWidth; + public int _pictureHeight; protected int _startPosX; protected int _startPosY; private readonly int _boatWidth = 185; diff --git a/Sailboat/Sailboat/FormBoatCollection.cs b/Sailboat/Sailboat/FormBoatCollection.cs index 0e7f5fa..7ab1f8e 100644 --- a/Sailboat/Sailboat/FormBoatCollection.cs +++ b/Sailboat/Sailboat/FormBoatCollection.cs @@ -1,21 +1,18 @@ -using Microsoft.Extensions.Logging; -using System; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; -using System.Diagnostics.Metrics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; -using System.Xml.Linq; -using Serilog; +using Microsoft.Extensions.Logging; using Sailboat.DrawingObjects; -using Sailboat.Exceptions; using Sailboat.Generics; using Sailboat.MovementStrategy; +using Sailboat.Exceptions; namespace Sailboat { @@ -23,7 +20,7 @@ namespace Sailboat { private readonly BoatsGenericStorage _storage; private readonly ILogger _logger; - public FormBoatCollection() + public FormBoatCollection(ILogger logger) { InitializeComponent(); _storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); @@ -34,12 +31,10 @@ namespace Sailboat { int index = listBoxStorages.SelectedIndex; listBoxStorages.Items.Clear(); - for (int i = 0; i < _storage.Keys.Count; i++) { listBoxStorages.Items.Add(_storage.Keys[i]); } - if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count)) { @@ -55,46 +50,63 @@ namespace Sailboat { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Коллекция не выбрана"); return; } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { return; } - FormBoatConfig form = new FormBoatConfig(pictureBoxCollection.Width, pictureBoxCollection.Height); - form.Show(); - Action? boatDelegate = new((plane) => + + var formBoatConfig = new FormBoatConfig(); + formBoatConfig.AddEvent(AddBoat); + formBoatConfig.Show(); + } + + private void AddBoat(DrawingBoat drawingBoat) + { + if (listBoxStorages.SelectedIndex == -1) { - if (obj + plane) + return; + } + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) + { + _logger.LogWarning("Добавление пустого объекта"); + return; + } + try + { + if (obj + drawingBoat) { MessageBox.Show("Объект добавлен"); pictureBoxCollection.Image = obj.ShowBoats(); + _logger.LogInformation($"Объект {obj.GetType()} добавлен"); } - else - { - MessageBox.Show("Не удалось добавить объект"); - } - }); - form.AddEvent(boatDelegate); + } + catch (StorageOverflowException ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); + } } private void buttonRemoveBoat_Click(object sender, EventArgs e) { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Удаление объекта из несуществующего набора"); return; } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { return; } - if (MessageBox.Show("Удалить объект?", "Удаление", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { + _logger.LogWarning("Отмена удаления объекта"); return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); @@ -103,16 +115,19 @@ namespace Sailboat if (obj - pos != null) { MessageBox.Show("Объект удален"); + _logger.LogInformation($"Удален объект с позиции {pos}"); pictureBoxCollection.Image = obj.ShowBoats(); } else { MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}"); } } catch (BoatNotFoundException ex) { MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}"); } } @@ -135,13 +150,14 @@ namespace Sailboat { if (string.IsNullOrEmpty(textBoxStorageName.Text)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Коллекция не добавлена, не все данные заполнены"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); - _logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}"); + + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e) @@ -154,15 +170,17 @@ namespace Sailboat { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Удаление невыбранного набора"); return; } string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; - if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _storage.DelSet(name); - ReloadObjects(); ; + ReloadObjects(); _logger.LogInformation($"Удален набор: {name}"); } + _logger.LogWarning("Отмена удаления набора"); } private void SaveToolStripMenuItem_Click(object sender, EventArgs e) @@ -172,13 +190,13 @@ namespace Sailboat try { _storage.SaveData(saveFileDialog.FileName); - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}"); } catch (Exception ex) { - MessageBox.Show($"Не сохранилось: {ex.Message}", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}"); } } } @@ -190,20 +208,14 @@ namespace Sailboat try { _storage.LoadData(openFileDialog.FileName); - MessageBox.Show("Загрузка прошла успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - Log.Information($"Файл {openFileDialog.FileName} успешно загружен"); - foreach (var collection in _storage.Keys) - { - listBoxStorages.Items.Add(collection); - } ReloadObjects(); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}"); } catch (Exception ex) { - Log.Warning("Не удалось загрузить"); - MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}"); } } } diff --git a/Sailboat/Sailboat/FormBoatConfig.cs b/Sailboat/Sailboat/FormBoatConfig.cs index db143ce..faef923 100644 --- a/Sailboat/Sailboat/FormBoatConfig.cs +++ b/Sailboat/Sailboat/FormBoatConfig.cs @@ -1,6 +1,4 @@ -using Sailboat.DrawingObjects; -using Sailboat.Entities; -using System; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -10,18 +8,19 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Sailboat.DrawingObjects; +using Sailboat.Generics; +using Sailboat.MovementStrategy; +using Sailboat.Entities; + namespace Sailboat { public partial class FormBoatConfig : Form { DrawingBoat? _boat = null; private event Action? EventAddBoat; - public int _pictureWidth { get; private set; } - public int _pictureHeight { get; private set; } - public FormBoatConfig(int pictureWidth, int pictureHeight) + public FormBoatConfig() { - _pictureWidth = pictureWidth; - _pictureHeight = pictureHeight; InitializeComponent(); panelBlack.MouseDown += PanelColor_MouseDown; panelPurple.MouseDown += PanelColor_MouseDown; @@ -68,7 +67,6 @@ namespace Sailboat private void PanelObject_DragEnter(object sender, DragEventArgs e) { - if (e.Data?.GetDataPresent(DataFormats.Text) ?? false) { e.Effect = DragDropEffects.Copy; @@ -85,12 +83,14 @@ namespace Sailboat { case "labelSimpleObject": _boat = new DrawingBoat((int)numericUpDownSpeed.Value, - (int)numericUpDownWeight.Value, Color.White, _pictureWidth, _pictureHeight); + (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, + pictureBoxObject.Height); break; case "labelModifiedObject": _boat = new DrawingSailboat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxHull.Checked, - checkBoxSail.Checked, _pictureWidth, _pictureHeight); + checkBoxSail.Checked, pictureBoxObject.Width, + pictureBoxObject.Height); break; } DrawBoat(); diff --git a/Sailboat/Sailboat/Program.cs b/Sailboat/Sailboat/Program.cs index c1bdb59..4e9c193 100644 --- a/Sailboat/Sailboat/Program.cs +++ b/Sailboat/Sailboat/Program.cs @@ -2,9 +2,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Serilog; -using Serilog.Events; -using Serilog.Formatting.Json; -using Serilog.Configuration; namespace Sailboat { @@ -16,25 +13,31 @@ namespace Sailboat [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++) + ApplicationConfiguration.Initialize(); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) { - pathNeed += path[i] + "\\"; + Application.Run(serviceProvider.GetRequiredService()); } - var configuration = new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile(path: $"{pathNeed}debug.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 FormBoatCollection()); + } + + 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}appSetting.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/Sailboat/Sailboat/Sailboat.csproj b/Sailboat/Sailboat/Sailboat.csproj index b2c4814..3569769 100644 --- a/Sailboat/Sailboat/Sailboat.csproj +++ b/Sailboat/Sailboat/Sailboat.csproj @@ -1,33 +1,35 @@  - - WinExe - net6.0-windows - enable - true - enable - + + WinExe + net6.0-windows + enable + true + enable + - - - - - - - - - - True - True - Resources.resx - - + + + + + + + + - - - ResXFileCodeGenerator - Resources.Designer.cs - - + + + True + True + Resources.resx + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + \ No newline at end of file diff --git a/Sailboat/Sailboat/StorageOverflowException.cs b/Sailboat/Sailboat/StorageOverflowException.cs index 15de1fe..5068217 100644 --- a/Sailboat/Sailboat/StorageOverflowException.cs +++ b/Sailboat/Sailboat/StorageOverflowException.cs @@ -1,16 +1,16 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; -using System.Runtime.Serialization; namespace Sailboat.Exceptions { [Serializable] internal class StorageOverflowException : ApplicationException { - public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: { count}") { } + public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { } public StorageOverflowException() : base() { } public StorageOverflowException(string message) : base(message) { } public StorageOverflowException(string message, Exception exception) diff --git a/Sailboat/Sailboat/appSetting.json b/Sailboat/Sailboat/appSetting.json new file mode 100644 index 0000000..3b03e95 --- /dev/null +++ b/Sailboat/Sailboat/appSetting.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": "Sailboat" + } + } +} \ No newline at end of file diff --git a/Sailboat/Sailboat/debug.json b/Sailboat/Sailboat/debug.json deleted file mode 100644 index 812a97c..0000000 --- a/Sailboat/Sailboat/debug.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "Serilog": { - "Using": [ "Serilog.Sinks.File" ], - "MinimumLevel": "Debug", - "WriteTo": [ - { - "Name": "File", - "Args": { "path": "log.txt" } - } - ], - "Properties": { - "Application": "Sample" - } - } -} \ No newline at end of file -- 2.25.1 From 75133affd5d9a0854fbad061015231b875ec7c2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=BE=D1=84=D1=8C=D1=8F=20=D0=AF=D0=BA=D0=BE=D0=B1?= =?UTF-8?q?=D1=87=D1=83=D0=BA?= Date: Wed, 27 Dec 2023 08:46:22 +0400 Subject: [PATCH 4/4] =?UTF-8?q?=D0=93=D0=BE=D1=82=D0=BE=D0=B2=D0=B0=D1=8F?= =?UTF-8?q?=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sailboat/Sailboat/DrawningSailboat.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Sailboat/Sailboat/DrawningSailboat.cs b/Sailboat/Sailboat/DrawningSailboat.cs index c9dda29..c53bda1 100644 --- a/Sailboat/Sailboat/DrawningSailboat.cs +++ b/Sailboat/Sailboat/DrawningSailboat.cs @@ -25,8 +25,7 @@ namespace Sailboat.DrawingObjects /// Признак наличия паруса /// Ширина картинки /// Высота картинки - public DrawingSailboat(int speed, double weight, Color bodyColor, Color additionalColor, bool hull, bool sail, int width, int height) : - base(speed, weight, bodyColor, width, height, 200, 160) + public DrawingSailboat(int speed, double weight, Color bodyColor, Color additionalColor, bool hull, bool sail, int width, int height) : base(speed, weight, bodyColor, width, height, 200, 160) { if (EntityBoat != null) { -- 2.25.1