diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs index 390debd..2d2deee 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectAirbus.Drawnings; +using ProjectAirbus.Exceptions; namespace ProjectAirbus.CollectionGenericObjects; @@ -35,7 +36,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); /// /// Конструктор @@ -96,8 +97,15 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningBus? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningBus? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException e) + { } + catch (PositionOutOfCollectionException e) + { } } return bitmap; diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AerodromService.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AerodromService.cs index 6f6b55d..78f9491 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AerodromService.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AerodromService.cs @@ -1,6 +1,7 @@ using ProjectAirbus.CollectionGenericObjects; using ProjectAirbus.Drawnings; using ProjectAirbus.CollectionGenericObjects; +using ProjectAirbus.Exceptions; namespace ProjectAirbus.CollectionGenericObjects; @@ -23,27 +24,17 @@ public class AerodromService : AbstractCompany protected override void DrawBackgound(Graphics g) { - Pen pen = new Pen(Color.LightBlue, 3); - int offsetX = 10; - int offsetY = -12; - int x = 1 + offsetX, y = _pictureHeight - _placeSizeHeight + offsetY; - numRows = 0; - while (y >= 0) + int width = _pictureWidth / _placeSizeWidth; + int height = _pictureHeight / _placeSizeHeight; + Pen pen = new(Color.Black, 2); + for (int i = 0; i < width + 1; i++) { - int numCols = 0; - while (x + _placeSizeWidth <= _pictureWidth) + for (int j = 0; j < height + 1; ++j) { - numCols++; - g.DrawLine(pen, x, y, x + _placeSizeWidth / 2, y); - g.DrawLine(pen, x, y, x, y + _placeSizeHeight + 8); - locCoord.Add(new Tuple(x, y)); - x += _placeSizeWidth + 2; + g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight); + g.DrawLine(pen, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight - _placeSizeHeight); } - numRows++; - x = 1 + offsetX; - y -= _placeSizeHeight + 5 + offsetY; } - } protected override void SetObjectsPosition() @@ -56,12 +47,13 @@ public class AerodromService : AbstractCompany for (int i = 0; i < (_collection?.Count ?? 0); i++) { - if (_collection.Get(i) != null) + try { _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); - _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 35); + _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 20); } - + catch (ObjectNotFoundException) { } + catch (PositionOutOfCollectionException e) { } if (curWidth > 0) curWidth--; else diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs index 8d24da5..9bf3716 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ using ProjectAirbus.CollectionGenericObjects; +using ProjectAirbus.Exceptions; namespace ProjectAirBus.CollectionGenericObjects; @@ -17,14 +18,15 @@ public class ListGenericObjects : ICollectionGenericObjects /// /// Максимально допустимое число объектов в списке /// - private int _maxCount; + private int _maxCount = 10; public int Count => _collection.Count; - public int MaxCount { set { if (value > 0) { _maxCount = value; } } get { return Count; } } + public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } public CollectionType GetCollectionType => CollectionType.List; + public int MaxCount { get; set; } /// /// Конструктор @@ -36,32 +38,34 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - - if (position >= Count || position < 0) return null; + //TODO выброс ошибки если выход за границу + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } public int Insert(T obj) { - - if (Count + 1 > _maxCount) return -1; + // TODO выброс ошибки если переполнение + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; } public int Insert(T obj, int position) { - - if (Count + 1 > _maxCount) return -1; - if (position < 0 || position > Count) return -1; + // TODO выброс ошибки если переполнение + // TODO выброс ошибки если за границу + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); - return 1; + return position; } public T? Remove(int position) { - - if (position < 0 || position > Count) return null; + + // TODO если выброс за границу + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); T? pos = _collection[position]; _collection.RemoveAt(position); return pos; diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs index 54ed212..58634ea 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,4 @@ - +using ProjectAirbus.Exceptions; namespace ProjectAirbus.CollectionGenericObjects; @@ -48,15 +48,16 @@ internal class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - - if (position >= _collection.Length || position < 0) - { return null; } + // TODO выброс ошибки если выход за границу + // TODO выброс ошибки если объект пустой + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } public int Insert(T obj) { - + // TODO выброс ошибки если переполнение int index = 0; while (index < _collection.Length) { @@ -65,52 +66,50 @@ internal class MassiveGenericObjects : ICollectionGenericObjects _collection[index] = obj; return index; } - - index++; + ++index; } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - - if (position >= _collection.Length || position < 0) - { return -1; } - - if (_collection[position] == null) + // TODO выброс ошибки если переполнение + // TODO выброс ошибки если выход за границу + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) { _collection[position] = obj; return position; } - int index; - - for (index = position + 1; index < _collection.Length; ++index) + int index = position + 1; + while (index < _collection.Length) { if (_collection[index] == null) { - _collection[position] = obj; - return position; + _collection[index] = obj; + return index; } + ++index; } - - for (index = position - 1; index >= 0; --index) + index = position - 1; + while (index >= 0) { if (_collection[index] == null) { - _collection[position] = obj; - return position; + _collection[index] = obj; + return index; } + --index; } - return -1; + throw new CollectionOverflowException(Count); } public T? Remove(int position) { - - if (position >= _collection.Length || position < 0) - { - return null; - } + // TODO выброс ошибки если выход за границу + // TODO выброс ошибки если объект пустой + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); T obj = _collection[position]; _collection[position] = null; return obj; diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs index 69db20c..fe193ee 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs @@ -2,6 +2,7 @@ using ProjectAirbus.CollectionGenericObjects; using ProjectAirbus.Drawnings; +using ProjectAirbus.Exceptions; using System.Text; @@ -10,41 +11,29 @@ namespace ProjectAirBus.CollectionGenericObjects; public class StorageCollection where T : DrawningBus -{/// - /// Словарь (хранилище) с коллекциями - /// - private Dictionary> _storages; - /// - /// Возвращение списка названий коллекций - /// +{ + + readonly Dictionary> _storages; + + public List Keys => _storages.Keys.ToList(); - /// - /// Ключевое слово, с которого должен начинаться файл - /// - private readonly string _collectionKey = "CollectionsStorage"; + private readonly string _collectionKey = "CollectionStorage"; - /// - /// Разделитель для записи ключа и значения элемента словаря - /// private readonly string _separatorForKeyValue = "|"; - /// - /// Разделитель для записей коллекции данных в файл - /// - private readonly string _separatorItems = ";"; + private readonly string _separatorItem = ";"; - /// - /// Конструктор - /// public StorageCollection() { _storages = new Dictionary>(); } + public void AddCollection(string name, CollectionType collectionType) { - + // TODO проверка, что name не пустой и нет в словаре записи с таким ключом + // TODO Прописать логику для добавления if (name == null || _storages.ContainsKey(name)) { return; } switch (collectionType) @@ -63,7 +52,7 @@ public class StorageCollection public void DelCollection(string name) { - + // TODO Прописать логику для удаления коллекции if (_storages.ContainsKey(name)) _storages.Remove(name); } @@ -73,122 +62,126 @@ public class StorageCollection { get { - + // TODO Продумать логику получения объекта if (name == null || !_storages.ContainsKey(name)) { return null; } return _storages[name]; } } - /// - /// Сохранение информации по самолетам в хранилище в файл - /// - /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } - - if (File.Exists(filename)) { File.Delete(filename); } + + StringBuilder sb = new(); - - - using FileStream fs = new(filename, FileMode.Create); - using StreamWriter streamWriter = new StreamWriter(fs); - streamWriter.Write(_collectionKey); - + sb.Append(_collectionKey); foreach (KeyValuePair> value in _storages) { - streamWriter.Write(Environment.NewLine); - - if (value.Value.Count == 0) - { - continue; + sb.Append(Environment.NewLine); + if (value.Value.Count == 0) + { + continue; } - streamWriter.Write(value.Key); - streamWriter.Write(_separatorForKeyValue); - streamWriter.Write(value.Value.GetCollectionType); - streamWriter.Write(_separatorForKeyValue); - streamWriter.Write(value.Value.MaxCount); - streamWriter.Write(_separatorForKeyValue); - + sb.Append(value.Key); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.GetCollectionType); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.MaxCount); + sb.Append(_separatorForKeyValue); foreach (T? item in value.Value.GetItems()) { string data = item?.GetDataForSave() ?? string.Empty; if (string.IsNullOrEmpty(data)) - { - continue; - } - - - streamWriter.Write(data); - streamWriter.Write(_separatorItems); - + { + continue; + } + sb.Append(data); + sb.Append(_separatorItem); } } - return true; + + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new UTF8Encoding().GetBytes(sb.ToString()); + fs.Write(info, 0, info.Length); + } - /// - /// Загрузка информации по кораблям в хранилище из файла - /// - /// - /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } - using (StreamReader sr = new StreamReader(filename)) + string bufferTextFromFile = ""; + using (FileStream fs = new(filename, FileMode.Open)) { - string? str; - str = sr.ReadLine(); - if (str != _collectionKey.ToString()) - return false; - - _storages.Clear(); - - while ((str = sr.ReadLine()) != null) + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new UTF8Encoding(true); + while (fs.Read(b, 0, b.Length) > 0) { - string[] record = str.Split(_separatorForKeyValue); - - - if (record.Length != 4) - { - continue; - } - - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - return false; - } - - collection.MaxCount = Convert.ToInt32(record[2]); - - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) - { - if (elem?.CreateDrawningBus() is T aircraft) - { - if (collection.Insert(aircraft) == -1) - return false; - } - } - - _storages.Add(record[0], collection); + bufferTextFromFile += temp.GetString(b); } } - return true; + + string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + if (strs.Length == 0 || strs == null) + { + throw new Exception("В файле нет данных"); + } + if (!strs[0].Equals(_collectionKey)) + { + throw new Exception("В файле неверные данные"); + } + + _storages.Clear(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) + { + continue; + } + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + if (collection == null) + { + throw new Exception("Не удалось создать коллекцию"); + } + collection.MaxCount = Convert.ToInt32(record[2]); + + string[] set = record[3].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + if (elem?.CreateDrawningBus() is T bus) + { + try + { + if (collection.Insert(bus) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3] ); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); + } + } + } + + _storages.Add(record[0], collection); + } + + } + private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) { return collectionType switch diff --git a/ProjectAirbus/ProjectAirbus/Exceptions/CollectionOverflowException.cs b/ProjectAirbus/ProjectAirbus/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..6b35d0c --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,22 @@ +using System.Runtime.Serialization; + +namespace ProjectAirbus.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] + +public class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество : " + count) { } + + public CollectionOverflowException() : base() { } + + public CollectionOverflowException(string message) : base(message) { } + + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + + protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + +} diff --git a/ProjectAirbus/ProjectAirbus/Exceptions/ObjectNotFoundException.cs b/ProjectAirbus/ProjectAirbus/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..b498b4d --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectAirbus.Exceptions; +/// +/// Класс, описывающий ошибку, что по указанной позиции нет элемента +/// +[Serializable] + +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int count) : base("В коллекции превышено допустимое количество : " + count) { } + + public ObjectNotFoundException() : base() { } + + public ObjectNotFoundException(string message) : base(message) { } + + public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { } + + protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/ProjectAirbus/ProjectAirbus/Exceptions/PositionOutOfCollectionException.cs b/ProjectAirbus/ProjectAirbus/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..42b445b --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,21 @@ +using System.Runtime.Serialization; + +namespace ProjectAirbus.Exceptions; +/// +/// Класс, описывающий ошибку выхода за границы коллекции +/// +[Serializable] + +internal class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int count) : base("В коллекции превышено допустимое количество : " + count) { } + + public PositionOutOfCollectionException() : base() { } + + public PositionOutOfCollectionException(string message) : base(message) { } + + public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } + + protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + +} diff --git a/ProjectAirbus/ProjectAirbus/FormBusCollection.Designer.cs b/ProjectAirbus/ProjectAirbus/FormBusCollection.Designer.cs index cd51ea8..2dc9566 100644 --- a/ProjectAirbus/ProjectAirbus/FormBusCollection.Designer.cs +++ b/ProjectAirbus/ProjectAirbus/FormBusCollection.Designer.cs @@ -140,6 +140,7 @@ buttonDelBus.TabIndex = 4; buttonDelBus.Text = "Удалить самолет"; buttonDelBus.UseVisualStyleBackColor = true; + buttonDelBus.Click += buttonDelBus_Click; // // maskedTextBox // diff --git a/ProjectAirbus/ProjectAirbus/FormBusCollection.cs b/ProjectAirbus/ProjectAirbus/FormBusCollection.cs index 620d116..3ca75db 100644 --- a/ProjectAirbus/ProjectAirbus/FormBusCollection.cs +++ b/ProjectAirbus/ProjectAirbus/FormBusCollection.cs @@ -1,6 +1,9 @@ -using ProjectAirbus.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectAirbus.CollectionGenericObjects; using ProjectAirbus.Drawnings; +using ProjectAirbus.Exceptions; using ProjectAirBus.CollectionGenericObjects; +using System.Windows.Forms; namespace ProjectAirbus; @@ -8,11 +11,15 @@ public partial class FormBusCollection : Form { private readonly StorageCollection _storageCollection; - private AbstractCompany? _company; - public FormBusCollection() + private AbstractCompany? _company = null; + private readonly ILogger _logger; + + public FormBusCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) @@ -20,10 +27,6 @@ public partial class FormBusCollection : Form panelCompanyTools.Enabled = false; } - - - - /// /// добавить самолет /// @@ -44,46 +47,52 @@ public partial class FormBusCollection : Form { return; } - - if (_company + bus != -1) + try { + var res = _company + bus; MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Объект добавлен под индексом {res}"); pictureBox1.Image = _company.Show(); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK, + MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } - - /// /// Удаление объекта /// /// /// - private void buttonDelPlane_Click(object sender, EventArgs e) + private void buttonDelBus_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) { return; } - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != + DialogResult.Yes) { return; } int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos != null) + try { + var res = _company - pos; MessageBox.Show("Объект удален"); + _logger.LogInformation($"Объект удален под индексом {pos}"); pictureBox1.Image = _company.Show(); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message, "Не удалось удалить объект", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } @@ -110,14 +119,14 @@ public partial class FormBusCollection : Form break; } } - if (bus == null) { return; } - - FormAirbus form = new(); - form.SetBus = bus; + FormAirbus form = new() + { + SetBus = bus + }; form.ShowDialog(); } @@ -143,7 +152,8 @@ public partial class FormBusCollection : Form /// private void buttonCollectionAdd_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) + if (string.IsNullOrEmpty(textBoxCollectionName.Text) || + (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; @@ -159,8 +169,18 @@ public partial class FormBusCollection : Form collectionType = CollectionType.List; } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); + try + { + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавление коллекции"); + RerfreshListBoxItems(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); + } + } /// /// Удаление коллекции @@ -169,18 +189,20 @@ public partial class FormBusCollection : Form /// private void buttonCollectionDel_Click(object sender, EventArgs e) { - - - if (listBoxCollection.SelectedItem == null) + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); return; } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != + DialogResult.Yes) { return; } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation("Коллекция удалена"); RerfreshListBoxItems(); } @@ -215,7 +237,8 @@ public partial class FormBusCollection : Form return; } - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + ICollectionGenericObjects? collection = + _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -226,6 +249,7 @@ public partial class FormBusCollection : Form { case "Хранилище": _company = new AerodromService(pictureBox1.Width, pictureBox1.Height, collection); + _logger.LogInformation("Компания создана"); break; } @@ -237,15 +261,17 @@ public partial class FormBusCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { + _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - else + catch (Exception ex) { MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } - } } @@ -253,17 +279,18 @@ public partial class FormBusCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - + _storageCollection.LoadData(openFileDialog.FileName); RerfreshListBoxItems(); + MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } - } } diff --git a/ProjectAirbus/ProjectAirbus/FormBusConfig.Designer.cs b/ProjectAirbus/ProjectAirbus/FormBusConfig.Designer.cs index a5c0169..2b4dffe 100644 --- a/ProjectAirbus/ProjectAirbus/FormBusConfig.Designer.cs +++ b/ProjectAirbus/ProjectAirbus/FormBusConfig.Designer.cs @@ -247,6 +247,7 @@ pictureBoxObject.Size = new Size(204, 121); pictureBoxObject.TabIndex = 1; pictureBoxObject.TabStop = false; + // // buttonAdd // diff --git a/ProjectAirbus/ProjectAirbus/FormBusConfig.cs b/ProjectAirbus/ProjectAirbus/FormBusConfig.cs index 5c843ee..69e3158 100644 --- a/ProjectAirbus/ProjectAirbus/FormBusConfig.cs +++ b/ProjectAirbus/ProjectAirbus/FormBusConfig.cs @@ -36,7 +36,7 @@ public partial class FormBusConfig : Form BusDelegate += busDelegate; } - + private void DrawObject() { Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height); @@ -73,8 +73,8 @@ public partial class FormBusConfig : Form } private void Panel_MouseDown(object? sender, MouseEventArgs e) - { - + { + (sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy); } @@ -126,7 +126,7 @@ public partial class FormBusConfig : Form private void ButtonAddAirbus_Click(object sender, EventArgs e) { - if(_bus != null) + if (_bus != null) { BusDelegate?.Invoke(_bus); Close(); diff --git a/ProjectAirbus/ProjectAirbus/Program.cs b/ProjectAirbus/ProjectAirbus/Program.cs index 34ef3f3..d642473 100644 --- a/ProjectAirbus/ProjectAirbus/Program.cs +++ b/ProjectAirbus/ProjectAirbus/Program.cs @@ -1,17 +1,44 @@ -namespace ProjectAirbus +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; + +namespace ProjectAirbus; + +internal static class Program { - internal static class Program + [STAThread] + static void Main() { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); - Application.Run(new FormBusCollection()); + Application.Run(serviceProvider.GetRequiredService()); } } + + 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}serilogConfig.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/ProjectAirbus/ProjectAirbus/ProjectAirbus.csproj b/ProjectAirbus/ProjectAirbus/ProjectAirbus.csproj index af03d74..4c8629a 100644 --- a/ProjectAirbus/ProjectAirbus/ProjectAirbus.csproj +++ b/ProjectAirbus/ProjectAirbus/ProjectAirbus.csproj @@ -8,6 +8,15 @@ enable + + + + + + + + + True @@ -23,4 +32,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectAirbus/ProjectAirbus/serilogConfig.json b/ProjectAirbus/ProjectAirbus/serilogConfig.json new file mode 100644 index 0000000..ffdff69 --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/serilogConfig.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": "Airbus" + } + } +} \ No newline at end of file