From b2c527eccde6eec8f462703f17fa3dffa381a391 Mon Sep 17 00:00:00 2001 From: Arkadiy Radaev Date: Wed, 13 Dec 2023 11:50:29 +0400 Subject: [PATCH] =?UTF-8?q?"=D0=92=D1=81=D1=8F=20=D1=81=D1=83=D1=82=D1=8C?= =?UTF-8?q?=20=D0=B2=20=D0=B4=D0=B5=D1=82=D0=B0=D0=BB=D1=8F=D1=85"=20-=20?= =?UTF-8?q?=D0=93=D1=83=D1=82...?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Catamaran/Catamaran.csproj | 7 +++ Catamaran/CatamaranNotFoundException.cs | 18 ++++++++ Catamaran/CatamaransGenericCollection.cs | 3 +- Catamaran/CatamaransGenericStorage.cs | 47 ++++++++++---------- Catamaran/ExtentionDrawningCatamaran.cs | 2 +- Catamaran/FormCatamaranCollection.cs | 56 ++++++++++++++++-------- Catamaran/Program.cs | 17 ++++--- Catamaran/SetGeneric.cs | 10 +++-- Catamaran/StorageOverflowException.cs | 19 ++++++++ 9 files changed, 123 insertions(+), 56 deletions(-) create mode 100644 Catamaran/CatamaranNotFoundException.cs create mode 100644 Catamaran/StorageOverflowException.cs diff --git a/Catamaran/Catamaran.csproj b/Catamaran/Catamaran.csproj index b57c89e..2028c8e 100644 --- a/Catamaran/Catamaran.csproj +++ b/Catamaran/Catamaran.csproj @@ -8,4 +8,11 @@ enable + + + + + + + \ No newline at end of file diff --git a/Catamaran/CatamaranNotFoundException.cs b/Catamaran/CatamaranNotFoundException.cs new file mode 100644 index 0000000..e3a9755 --- /dev/null +++ b/Catamaran/CatamaranNotFoundException.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Catamaran +{ + internal class CatamaranNotFoundException : ApplicationException + { + public CatamaranNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public CatamaranNotFoundException() : base() { } + public CatamaranNotFoundException(string message) : base(message) { } + public CatamaranNotFoundException(string message, Exception exception) : base(message, exception) { } + protected CatamaranNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/Catamaran/CatamaransGenericCollection.cs b/Catamaran/CatamaransGenericCollection.cs index 38aa886..5bf691f 100644 --- a/Catamaran/CatamaransGenericCollection.cs +++ b/Catamaran/CatamaransGenericCollection.cs @@ -41,8 +41,7 @@ namespace Catamaran public static T? operator -(CatamaransGenericCollection collect, int pos) { T? obj = collect._collection[pos]; - if (obj != null) - collect._collection.Remove(pos); + collect._collection.Remove(pos); return obj; } diff --git a/Catamaran/CatamaransGenericStorage.cs b/Catamaran/CatamaransGenericStorage.cs index a1f6440..bd638db 100644 --- a/Catamaran/CatamaransGenericStorage.cs +++ b/Catamaran/CatamaransGenericStorage.cs @@ -22,7 +22,15 @@ namespace Catamaran private readonly char _separatorRecords = ';'; private static readonly char _separatorForObject = ':'; - + + public CatamaransGenericStorage(int pictureWidth, int pictureHeight) + { + _catStorages = new Dictionary>(); + _pictureWidth = pictureWidth; + _pictureHeight = pictureHeight; + } + public bool SaveData(string filename) { if (File.Exists(filename)) @@ -30,7 +38,8 @@ namespace Catamaran File.Delete(filename); } StringBuilder data = new(); - foreach (KeyValuePair> record in _catStorages) + foreach (KeyValuePair> record in _catStorages) { StringBuilder records = new(); foreach (DrawningCatamaran? elem in record.Value.GetCatamarans) @@ -39,12 +48,12 @@ namespace Catamaran } data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); } + if (data.Length == 0) { - return false; + throw new Exception("Невалиданя операция, нет данных для сохранения"); } - - string toWrite = $"catamaransStorage{Environment.NewLine}{data}"; + string toWrite = $"CatamaranStorage{Environment.NewLine}{data}"; var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); using (StreamWriter sw = new(filename)) @@ -54,32 +63,28 @@ namespace Catamaran sw.WriteLine(str); } } - return true; } - + public bool LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new IOException("Файл не найден"); } - using (StreamReader sr = new(filename)) { string str = sr.ReadLine(); 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("catamaransStorage")) + if (!strs[0].StartsWith("CatamaranStorage")) { - return false; + throw new IOException("Неверный формат данных"); } - _catStorages.Clear(); - do { string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); @@ -89,11 +94,12 @@ namespace Catamaran continue; } CatamaransGenericCollection collection = new(_pictureWidth, _pictureHeight); - string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + string[] set = record[1].Split(_separatorRecords, + StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { DrawningCatamaran? catamaran = - elem?.CreateDrawningCatamran(_separatorForObject, _pictureWidth, _pictureHeight); + elem?.CreateDrawningCatamaran(_separatorForObject, _pictureWidth, _pictureHeight); if (catamaran != null) { if (!(collection + catamaran)) @@ -110,15 +116,6 @@ namespace Catamaran return true; } - public CatamaransGenericStorage(int pictureWidth, int pictureHeight) - { - _catStorages = new Dictionary>(); - _pictureWidth = pictureWidth; - _pictureHeight = pictureHeight; - } - public void AddSet(string name) { _catStorages.Add(name, new CatamaransGenericCollection(_pictureWidth, _pictureHeight)); diff --git a/Catamaran/ExtentionDrawningCatamaran.cs b/Catamaran/ExtentionDrawningCatamaran.cs index 075f245..21c1598 100644 --- a/Catamaran/ExtentionDrawningCatamaran.cs +++ b/Catamaran/ExtentionDrawningCatamaran.cs @@ -9,7 +9,7 @@ namespace Catamaran public static class ExtentionDrawningCatamaran { - public static DrawningCatamaran? CreateDrawningCatamran(this string info, char + public static DrawningCatamaran? CreateDrawningCatamaran(this string info, char separatorForObject, int width, int height) { string[] strs = info.Split(separatorForObject); diff --git a/Catamaran/FormCatamaranCollection.cs b/Catamaran/FormCatamaranCollection.cs index 5b68a80..5e30fac 100644 --- a/Catamaran/FormCatamaranCollection.cs +++ b/Catamaran/FormCatamaranCollection.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -7,6 +8,9 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Serilog; + + namespace Catamaran { @@ -89,16 +93,18 @@ namespace Catamaran form.Show(); Action? catamaranDelegate = new((c) => { - bool q = (obj + c); - if (q) + try { + bool q = obj + c; MessageBox.Show("Объект добавлен"); + Log.Information($"Добавлен объект в коллекцию {SetslistBox.SelectedItem.ToString() ?? string.Empty}"); c.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height); pictureBoxCollection.Image = obj.ShowCats(); } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + Log.Warning($"Коллекция {SetslistBox.SelectedItem.ToString() ?? string.Empty} переполнена"); + MessageBox.Show(ex.Message); } }); form.AddEvent(catamaranDelegate); @@ -122,15 +128,23 @@ namespace Catamaran { return; } - int pos = Convert.ToInt32(maskedTextBox.Text); - if (obj - pos != null) + try { + int pos = Convert.ToInt32(maskedTextBox.Text); + var q = obj - pos; MessageBox.Show("Объект удален"); + Log.Information($"Удален объект из коллекции {SetslistBox.SelectedItem.ToString() ?? string.Empty} по номеру {pos}"); pictureBoxCollection.Image = obj.ShowCats(); } - else + catch (CatamaranNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + Log.Warning($"Не получилось удалить объект из коллекции {SetslistBox.SelectedItem.ToString() ?? string.Empty}"); + MessageBox.Show(ex.Message); + } + catch (FormatException ex) + { + Log.Warning($"Было введено не число"); + MessageBox.Show("Введите число"); } } private void ButtonRefreshCollection_Click(object sender, EventArgs e) @@ -152,36 +166,42 @@ namespace Catamaran { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _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); + } } } - private void LoadToolStripMenuItem_Click(object sender, EventArgs e) { 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) { SetslistBox.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/Catamaran/Program.cs b/Catamaran/Program.cs index 6d95577..e15d716 100644 --- a/Catamaran/Program.cs +++ b/Catamaran/Program.cs @@ -1,18 +1,23 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; + namespace Catamaran { internal static class Program { /// - /// The main entry point for the application. + /// The main entry point for the application. /// [STAThread] - static void Main() + 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 FormCatamaranCollection()); } - } } \ No newline at end of file diff --git a/Catamaran/SetGeneric.cs b/Catamaran/SetGeneric.cs index 4a38291..10ebb7b 100644 --- a/Catamaran/SetGeneric.cs +++ b/Catamaran/SetGeneric.cs @@ -22,7 +22,7 @@ namespace Catamaran public bool Insert(T catamaran) { if (_places.Count == _maxCount) - return false; + throw new StorageOverflowException(_maxCount); Insert(catamaran, 0); return true; } @@ -30,6 +30,8 @@ namespace Catamaran public bool Insert(T catamaran, int position) { if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) + throw new StorageOverflowException(_maxCount); + if (!(position >= 0 && position <= Count)) return false; _places.Insert(position, catamaran); return true; @@ -38,7 +40,7 @@ namespace Catamaran public bool Remove(int position) { if (!(position >= 0 && position < Count) || _places[position] == null) - return false; + throw new CatamaranNotFoundException(position); _places[position] = null; return true; } @@ -58,12 +60,12 @@ namespace Catamaran return; } } - public IEnumerable GetCatamarans(int? maxMonorails = null) + public IEnumerable GetCatamarans(int? maxCatamarans = null) { for (int i = 0; i < _places.Count; ++i) { yield return _places[i]; - if (maxMonorails.HasValue && i == maxMonorails.Value) + if (maxCatamarans.HasValue && i == maxCatamarans.Value) { yield break; } diff --git a/Catamaran/StorageOverflowException.cs b/Catamaran/StorageOverflowException.cs new file mode 100644 index 0000000..0c71436 --- /dev/null +++ b/Catamaran/StorageOverflowException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Catamaran +{ + [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