diff --git a/lainer/Lainer1/FormLainerCollection.cs b/lainer/Lainer1/FormLainerCollection.cs index 61d511f..8804c79 100644 --- a/lainer/Lainer1/FormLainerCollection.cs +++ b/lainer/Lainer1/FormLainerCollection.cs @@ -1,4 +1,17 @@ -using ProjectLainer.DrawningObjects; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Reflection.Metadata.Ecma335; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.Xml.Linq; +using Microsoft.Extensions.Logging; +using ProjectLainer.DrawningObjects; +using ProjectLainer.Exceptions; using ProjectLainer.Generics; using ProjectLainer.MovementStrategy; @@ -7,17 +20,17 @@ namespace ProjectLainer public partial class FormLainerCollection : Form { private readonly LainersGenericStorage _storage; - public FormLainerCollection() + private readonly ILogger _logger; + public FormLainerCollection(ILogger logger) { InitializeComponent(); - _storage = new LainersGenericStorage(pictureBoxCollection.Width, - pictureBoxCollection.Height); + _storage = new LainersGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } private void ReloadObjects() { int index = listBoxStorages.SelectedIndex; listBoxStorages.Items.Clear(); - foreach (string key in _storage.Keys) { listBoxStorages.Items.Add(key); @@ -29,7 +42,7 @@ namespace ProjectLainer { listBoxStorages.SelectedIndex = index; } - } + } } private void ButtonAddObject_Click(object sender, EventArgs e) { @@ -41,6 +54,8 @@ namespace ProjectLainer } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); + } private void ButtonDelObject_Click(object sender, EventArgs e) { @@ -48,11 +63,13 @@ namespace ProjectLainer { return; } - if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show($"Удалить объект {name}?", "Удаление", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() - ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } private void ButtonAddLainer_Click(object sender, EventArgs e) @@ -76,8 +93,7 @@ namespace ProjectLainer { return; } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { return; @@ -88,14 +104,23 @@ namespace ProjectLainer return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowLainers(); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowLainers(); + _logger.LogInformation($"удален лайнер из набора :{listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (LainerNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning("ошибка лайнер не найден"); } } private void ButtonRefreshCollection_Click(object sender, EventArgs e) @@ -116,7 +141,7 @@ namespace ProjectLainer { pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowLainers(); } - private void AddLainer(DrawingEntity lainer) + private void AddLainer(DrawingLainer lainer) { if (listBoxStorages.SelectedIndex == -1) { @@ -127,29 +152,37 @@ namespace ProjectLainer { return; } - if (obj + lainer) + try { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowLainers(); + if (obj + lainer) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowLainers(); + _logger.LogInformation($"добавлен лайнер в набор: {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } } - else + catch (OverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning("ошибка переполнения"); } } private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { 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); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -157,15 +190,16 @@ namespace ProjectLainer { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); foreach (var collection in _storage.Keys) { listBoxStorages.Items.Add(collection); } } - else + catch (Exception) { MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } diff --git a/lainer/Lainer1/LainerGenericCollection.cs b/lainer/Lainer1/LainerGenericCollection.cs index 3939af8..b34730e 100644 --- a/lainer/Lainer1/LainerGenericCollection.cs +++ b/lainer/Lainer1/LainerGenericCollection.cs @@ -4,7 +4,7 @@ using ProjectLainer.DrawningObjects; namespace ProjectLainer.Generics { internal class LainersGenericCollection - where T : DrawingEntity + where T : DrawingLainer where U : IMoveableObject { private readonly int _pictureWidth; @@ -12,6 +12,7 @@ namespace ProjectLainer.Generics private readonly int _placeSizeWidth = 210; private readonly int _placeSizeHeight = 90; private readonly SetGeneric _collection; + public IEnumerable GetLainers => _collection.GetLainers(); public LainersGenericCollection(int picWidth, int picHeight) { int width = picWidth / _placeSizeWidth; @@ -23,16 +24,16 @@ namespace ProjectLainer.Generics public static bool operator +(LainersGenericCollection 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 -(LainersGenericCollection 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) @@ -74,8 +75,6 @@ namespace ProjectLainer.Generics lainer.SetPosition((inRow - 1 - (i % inRow)) * _placeSizeWidth, i / inRow * _placeSizeHeight); lainer.DrawTransport(g); - - } i++; } diff --git a/lainer/Lainer1/LainerNotFoundException.cs b/lainer/Lainer1/LainerNotFoundException.cs new file mode 100644 index 0000000..4249b77 --- /dev/null +++ b/lainer/Lainer1/LainerNotFoundException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectLainer.Exceptions +{ + [Serializable] + internal class LainerNotFoundException : ApplicationException + { + public LainerNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public LainerNotFoundException() : base() { } + public LainerNotFoundException(string message) : base(message) { } + public LainerNotFoundException(string message, Exception exception) : base(message, exception) + { } + protected LainerNotFoundException(SerializationInfo info, + StreamingContext contex) : base(info, contex) { } + } +} \ No newline at end of file diff --git a/lainer/Lainer1/LainersGenericStorage.cs b/lainer/Lainer1/LainersGenericStorage.cs index 1cdb237..4d6ce73 100644 --- a/lainer/Lainer1/LainersGenericStorage.cs +++ b/lainer/Lainer1/LainersGenericStorage.cs @@ -1,16 +1,18 @@ using ProjectLainer.DrawningObjects; using ProjectLainer.MovementStrategy; +using System.Text; + namespace ProjectLainer.Generics { internal class LainersGenericStorage { - + readonly Dictionary> _lainerStorages; - + public List Keys => _lainerStorages.Keys.ToList(); - + private readonly int _pictureWidth; - + private readonly int _pictureHeight; public LainersGenericStorage(int pictureWidth, int pictureHeight) { @@ -18,22 +20,21 @@ namespace ProjectLainer.Generics _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } - + public void AddSet(string name) { _lainerStorages.Add(name, new LainersGenericCollection(_pictureWidth, _pictureHeight)); } - + public void DelSet(string name) { if (!_lainerStorages.ContainsKey(name)) { return; } - _lainerStorages.Remove(name); } - + public LainersGenericCollection? this[string ind] { get @@ -48,18 +49,17 @@ namespace ProjectLainer.Generics private static readonly char _separatorForKeyValue = '|'; private readonly char _separatorRecords = ';'; private static readonly char _separatorForObject = ':'; - public bool SaveData(string filename) + public void SaveData(string filename) { - if (File.Exists(filename)) { File.Delete(filename); } StringBuilder data = new(); - foreach (KeyValuePair> record in _lainerStorages) + foreach (KeyValuePair> record in _lainerStorages) { StringBuilder records = new(); - foreach (DrawingLainer? elem in record.Value.GetLainers) + foreach (DrawingEntity? elem in record.Value.GetLainers) { records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); } @@ -67,19 +67,18 @@ namespace ProjectLainer.Generics } if (data.Length == 0) { - return false; + throw new ArgumentException("Невалиданя операция, нет данных для сохранения"); } using (StreamWriter sw = new(filename)) { sw.WriteLine($"LainerStorage{Environment.NewLine}{data}"); } - return true; } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new NullReferenceException("Файл не найден"); } using (StreamReader sr = new(filename)) { @@ -87,31 +86,32 @@ namespace ProjectLainer.Generics var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { - return false; + throw new NullReferenceException("нет данных для загрузки"); } if (!strs[0].StartsWith("LainerStorage")) { - return false; + throw new ArgumentException("неверный фориат данных"); } _lainerStorages.Clear(); do { string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 1) + if (record.Length != 2) { str = sr.ReadLine(); continue; } - LainersGenericCollection collection = new(_pictureWidth, _pictureHeight); + LainersGenericCollection collection = new(_pictureWidth, _pictureHeight); string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - DrawingLainer? lainer = elem?.CreateDrawningLainer(_separatorForObject, _pictureWidth, _pictureHeight); + DrawingEntity? lainer = elem?.CreateDrawningLainer(_separatorForObject, _pictureWidth, _pictureHeight); if (lainer != null) { if (!(collection + lainer)) { - return false; + throw new IOException("Ошибка добавления в коллекцию"); + } } } @@ -119,7 +119,6 @@ namespace ProjectLainer.Generics str = sr.ReadLine(); } while (str != null); } - return true; } } } diff --git a/lainer/Lainer1/StorageOverflowException.cs b/lainer/Lainer1/StorageOverflowException.cs new file mode 100644 index 0000000..e519c2a --- /dev/null +++ b/lainer/Lainer1/StorageOverflowException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectLainer.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) { } + } + +}