diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs index c7ad6bf..707164c 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,6 @@ -using ProjectMotorboat.Drownings; + +using ProjectMotorboat.Drownings; +using ProjectMotorboat.Exceptions; namespace ProjectMotorboat.CollectionGenericObjects; @@ -15,9 +17,8 @@ public abstract class AbstractCompany protected ICollectionGenericObjects? _collection = null; - - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) { _pictureWidth = picWidth; @@ -48,8 +49,15 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningBoat? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningBoat? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException e) + { } + catch (PositionOutOfCollectionException e) + { } } return bitmap; diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/CollectionType.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/CollectionType.cs index 5d33f5c..0ba2999 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/CollectionType.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/CollectionType.cs @@ -1,5 +1,4 @@ - -namespace ProjectMotorboat.CollectionGenericObjects; +namespace ProjectMotorboat.CollectionGenericObjects; public enum CollectionType { diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/HarborService.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/HarborService.cs index 92b0618..b262de5 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/HarborService.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/HarborService.cs @@ -1,5 +1,5 @@ - -using ProjectMotorboat.Drownings; +using ProjectMotorboat.Drownings; +using ProjectMotorboat.Exceptions; namespace ProjectMotorboat.CollectionGenericObjects; @@ -36,12 +36,13 @@ public class HarborService : 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 * boatWidth + 20, boatHeight * _placeSizeHeight + 20); } - + catch (ObjectNotFoundException) { } + catch (PositionOutOfCollectionException e) { } if (boatWidth < width - 1) boatWidth++; else diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ICollectionGenericObjects.cs index 21b201c..9434625 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,5 +1,4 @@ - -namespace ProjectMotorboat.CollectionGenericObjects; +namespace ProjectMotorboat.CollectionGenericObjects; public interface ICollectionGenericObjects diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs index 0a0c710..3b8480f 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs @@ -1,13 +1,16 @@ -namespace ProjectMotorboat.CollectionGenericObjects; +using ProjectMotorboat.Exceptions; +namespace ProjectMotorboat.CollectionGenericObjects; public class ListGenericObjects : ICollectionGenericObjects where T : class { + private readonly List _collection; public CollectionType GetCollectionType => CollectionType.List; + private int _maxCount; public int Count => _collection.Count; @@ -32,33 +35,33 @@ where T : class _collection = new(); } - public T? Get(int position) + public T Get(int position) { - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } - public int Insert(T obj) { - if (Count + 1 > _maxCount) return -1; + 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; + 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) + public T Remove(int position) { - if (position < 0 || position > Count) return null; - T? pos = _collection[position]; + + if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; _collection.RemoveAt(position); - return pos; + return obj; } public IEnumerable GetItems() diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs index 4eef7ae..fb824d5 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,8 @@ -namespace ProjectMotorboat.CollectionGenericObjects; + + +using ProjectMotorboat.Exceptions; + +namespace ProjectMotorboat.CollectionGenericObjects; public class MassiveGenericObjects : ICollectionGenericObjects where T : class { @@ -38,15 +42,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position < 0 || position >= _collection.Length) - { - return null; - } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } public int Insert(T obj) { - for (int i = 0; i < _collection.Length; i++) + for (int i = 0; i < Count; i++) { if (_collection[i] == null) { @@ -55,51 +57,55 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - if (position < 0 || position >= _collection.Length) { return position; } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) + if (_collection[position] != null) { - _collection[position] = obj; - return position; - } - else - { - for (int i = position + 1; i < _collection.Length; i++) + bool pushed = false; + for (int index = position + 1; index < Count; index++) { - if (_collection[i] == null) + if (_collection[index] == null) { - _collection[i] = obj; - return i; + position = index; + pushed = true; + break; } } - for (int i = position - 1; i >= 0; i--) + if (!pushed) { - if (_collection[i] == null) + for (int index = position - 1; index >= 0; index--) { - _collection[i] = obj; - return i; + if (_collection[index] == null) + { + position = index; + pushed = true; + break; + } } } - } - return -1; + if (!pushed) + { + throw new CollectionOverflowException(Count); + } + } + _collection[position] = obj; + return position; } public T Remove(int position) { - if (position < 0 || position >= _collection.Length) - { - return null; - } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - T? obj = _collection[position]; + if (_collection[position] == null) throw new ObjectNotFoundException(position); + + T? temp = _collection[position]; _collection[position] = null; - - return obj; + return temp; } public IEnumerable GetItems() @@ -113,3 +119,4 @@ public class MassiveGenericObjects : ICollectionGenericObjects + diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs index 5652781..93aaf8b 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs @@ -1,6 +1,6 @@ using ProjectMotorboat.Drownings; +using ProjectMotorboat.Exceptions; using System.Text; - namespace ProjectMotorboat.CollectionGenericObjects; public class StorageCollection @@ -19,7 +19,6 @@ public class StorageCollection public void AddCollection(string name, CollectionType collectionType) { - if (name == null || _storages.ContainsKey(name)) { return; } switch (collectionType) @@ -38,7 +37,7 @@ public class StorageCollection public void DelCollection(string name) { - + // TODO Прописать логику для удаления коллекции if (_storages.ContainsKey(name)) _storages.Remove(name); } @@ -48,7 +47,7 @@ public class StorageCollection { get { - + // TODO Продумать логику получения объекта if (name == null || !_storages.ContainsKey(name)) { return null; } return _storages[name]; } @@ -60,19 +59,21 @@ public class StorageCollection private readonly string _separatorItems = ";"; - - public bool SaveData(string filename) + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } - if (File.Exists(filename)) { File.Delete(filename); } - using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); @@ -80,7 +81,6 @@ public class StorageCollection { StringBuilder sb = new(); sb.Append(Environment.NewLine); - if (value.Value.Count == 0) { continue; @@ -106,31 +106,35 @@ public class StorageCollection } - return true; } - - public bool LoadData(string filename) + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } using (StreamReader fs = File.OpenText(filename)) { string str = fs.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new Exception("В файле нет данных"); } if (!str.StartsWith(_collectionKey)) { - return false; + throw new Exception("В файле неверные данные"); } _storages.Clear(); string strs = ""; while ((strs = fs.ReadLine()) != null) { + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); if (record.Length != 4) { @@ -140,23 +144,30 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningBoat() is T boat) + if (elem?.CreateDrawningBoat() is T track) { - if (collection.Insert(boat) == -1) + try { - return false; + if (collection.Insert(track) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } } _storages.Add(record[0], collection); } - return true; + } } private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) diff --git a/ProjectMotorboat/ProjectMotorboat/Drownings/DirectionType.cs b/ProjectMotorboat/ProjectMotorboat/Drownings/DirectionType.cs index 5ef15f9..8736b4f 100644 --- a/ProjectMotorboat/ProjectMotorboat/Drownings/DirectionType.cs +++ b/ProjectMotorboat/ProjectMotorboat/Drownings/DirectionType.cs @@ -1,4 +1,5 @@  + namespace ProjectMotorboat.Drownings { public enum DirectionType diff --git a/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningBoat.cs b/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningBoat.cs index d117ab8..dfd9d01 100644 --- a/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningBoat.cs +++ b/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningBoat.cs @@ -1,4 +1,6 @@ using ProjectMotorboat.Entities; + + namespace ProjectMotorboat.Drownings; public class DrawningBoat @@ -108,14 +110,14 @@ public class DrawningBoat } switch (direction) { - + case DirectionType.Left: if (_startPosX.Value - EntityBoat.Step > 0) { _startPosX -= (int)EntityBoat.Step; } return true; - + case DirectionType.Up: if (_startPosY.Value - EntityBoat.Step > 0) { @@ -129,7 +131,7 @@ public class DrawningBoat _startPosX += (int)EntityBoat.Step; } return true; - + case DirectionType.Down: if (_startPosY.Value + EntityBoat.Step + _drawningBoatHeight < _pictureHeight) { @@ -149,7 +151,7 @@ public class DrawningBoat Pen pen = new(Color.Black); Brush mainBrush = new SolidBrush(EntityBoat.BodyColor); - + Point[] hull = new Point[] { new Point(_startPosX.Value + 5, _startPosY.Value + 0), @@ -161,6 +163,7 @@ public class DrawningBoat g.FillPolygon(mainBrush, hull); g.DrawPolygon(pen, hull); + Brush blockBrush = new SolidBrush(EntityBoat.BodyColor); g.FillRectangle(blockBrush, _startPosX.Value + 20, _startPosY.Value + 15, 80, 40); g.DrawRectangle(pen, _startPosX.Value + 20, _startPosY.Value + 15, 80, 40); diff --git a/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningMotorboat.cs b/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningMotorboat.cs index a4c54fd..3c5a389 100644 --- a/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningMotorboat.cs +++ b/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningMotorboat.cs @@ -26,15 +26,12 @@ public class DrawningMotorboat : DrawningBoat Brush additionalBrush = new SolidBrush(motorboat.AdditionalColor); base.DrawTransport(g); - - if (motorboat.Glass) { Brush glassBrush = new SolidBrush(Color.LightBlue); g.FillEllipse(glassBrush, _startPosX.Value + 20, _startPosY.Value + 15, 100, 40); g.DrawEllipse(pen, _startPosX.Value + 20, _startPosY.Value + 15, 100, 40); } - if (motorboat.Motor) { Brush engineBrush = new diff --git a/ProjectMotorboat/ProjectMotorboat/Drownings/ExtentionDrawningBoat.cs b/ProjectMotorboat/ProjectMotorboat/Drownings/ExtentionDrawningBoat.cs index 4106627..b100371 100644 --- a/ProjectMotorboat/ProjectMotorboat/Drownings/ExtentionDrawningBoat.cs +++ b/ProjectMotorboat/ProjectMotorboat/Drownings/ExtentionDrawningBoat.cs @@ -1,9 +1,15 @@ using ProjectMotorboat.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; namespace ProjectMotorboat.Drownings; public static class ExtentionDrawningBoat { private static readonly string _separatorForObject = ":"; + public static DrawningBoat? CreateDrawningBoat(this string info) { string[] strs = info.Split(_separatorForObject); diff --git a/ProjectMotorboat/ProjectMotorboat/Exceptions/CollectionOverflowException.cs b/ProjectMotorboat/ProjectMotorboat/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..b7f71c2 --- /dev/null +++ b/ProjectMotorboat/ProjectMotorboat/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,18 @@ + +using System.Runtime.Serialization; + +namespace ProjectMotorboat.Exceptions; + +[Serializable] +internal 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/ProjectMotorboat/ProjectMotorboat/Exceptions/ObjectNotFoundException.cs b/ProjectMotorboat/ProjectMotorboat/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..07c8c83 --- /dev/null +++ b/ProjectMotorboat/ProjectMotorboat/Exceptions/ObjectNotFoundException.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 ProjectMotorboat.Exceptions; +[Serializable] +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + + 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) { } +} \ No newline at end of file diff --git a/ProjectMotorboat/ProjectMotorboat/Exceptions/PositionOutOfCollectionException.cs b/ProjectMotorboat/ProjectMotorboat/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..093c397 --- /dev/null +++ b/ProjectMotorboat/ProjectMotorboat/Exceptions/PositionOutOfCollectionException.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 ProjectMotorboat.Exceptions; +[Serializable] + +internal class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { } + + 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/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs index 13dc2d2..c11963e 100644 --- a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs +++ b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs @@ -1,48 +1,62 @@ -using ProjectMotorboat.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectMotorboat.CollectionGenericObjects; using ProjectMotorboat.Drownings; +using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar; namespace ProjectMotorboat; + public partial class FormBoatCollection : Form { private readonly StorageCollection _storageCollection; private AbstractCompany? _company = null; - public FormBoatCollection() + + private readonly ILogger _logger; + + public FormBoatCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } + + private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) { panelCompanyTools.Enabled = false; } + + private void ButtonAddBoat_Click(object sender, EventArgs e) { FormBoatConfig form = new(); - + form.Show(); form.AddEvent(SetBoat); - form.Show(); } - private void SetBoat(DrawningBoat? boat) + private void SetBoat(DrawningBoat boat) { if (_company == null || boat == null) { return; } - - if (_company + boat != -1) + try { + var res = _company + boat; MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Объект добавлен под индексом {res}"); pictureBox.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 ButtonRemoveBoat_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) @@ -50,23 +64,30 @@ public partial class FormBoatCollection : Form 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}"); pictureBox.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 ButtonGoToCheck_Click(object sender, EventArgs e) { if (_company == null) @@ -85,12 +106,10 @@ public partial class FormBoatCollection : Form break; } } - if (boat == null) { return; } - FormMotorboat form = new() { SetBoat = boat @@ -98,6 +117,7 @@ public partial class FormBoatCollection : Form form.ShowDialog(); } + private void ButtonRefresh_Click(object sender, EventArgs e) { if (_company == null) @@ -110,7 +130,8 @@ public partial class FormBoatCollection : 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; @@ -126,22 +147,36 @@ public partial class FormBoatCollection : 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); + } + } 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(); } @@ -166,7 +201,8 @@ public partial class FormBoatCollection : Form return; } - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + ICollectionGenericObjects? collection = + _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -177,24 +213,27 @@ public partial class FormBoatCollection : Form { case "Хранилище": _company = new HarborService(pictureBox.Width, pictureBox.Height, collection); + _logger.LogInformation("Компания создана"); break; } panelCompanyTools.Enabled = true; RerfreshListBoxItems(); } - private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { 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); } } } @@ -203,15 +242,19 @@ public partial class FormBoatCollection : 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); } } } -} \ No newline at end of file + +} diff --git a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.resx b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.resx index a4f11d6..42ce85b 100644 --- a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.resx +++ b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.resx @@ -127,6 +127,6 @@ 310, 17 - 25 + 51 \ No newline at end of file diff --git a/ProjectMotorboat/ProjectMotorboat/FormBoatConfig.cs b/ProjectMotorboat/ProjectMotorboat/FormBoatConfig.cs index 8de01e3..9f80f39 100644 --- a/ProjectMotorboat/ProjectMotorboat/FormBoatConfig.cs +++ b/ProjectMotorboat/ProjectMotorboat/FormBoatConfig.cs @@ -1,6 +1,5 @@ using ProjectMotorboat.Drownings; using ProjectMotorboat.Entities; - namespace ProjectMotorboat { public partial class FormBoatConfig : Form @@ -72,11 +71,9 @@ namespace ProjectMotorboat private void Panel_MouseDown(object? sender, MouseEventArgs e) { - (sender as Control)?.DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy); } - private void LabelBodyColor_DragEnter(object sender, DragEventArgs e) { if (e.Data?.GetDataPresent(typeof(Color)) ?? false) diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/AbstractStrategy.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/AbstractStrategy.cs index 3a1d329..dff9ae5 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/AbstractStrategy.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/AbstractStrategy.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - + namespace ProjectMotorboat.MovementStrategy; diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/IMoveableObject.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/IMoveableObject.cs index 898afa6..593b279 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/IMoveableObject.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/IMoveableObject.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + namespace ProjectMotorboat.MovementStrategy; diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveToBorder.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveToBorder.cs index 9004dfc..03b0866 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveToBorder.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveToBorder.cs @@ -1,4 +1,5 @@  + namespace ProjectMotorboat.MovementStrategy; public class MoveToBorder : AbstractStrategy { diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveableBoat.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveableBoat.cs index 6e59fee..0b43cfe 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveableBoat.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveableBoat.cs @@ -1,9 +1,5 @@ using ProjectMotorboat.Drownings; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + namespace ProjectMotorboat.MovementStrategy; diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MovementDirection.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MovementDirection.cs index 329e8d9..a79ea1f 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MovementDirection.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MovementDirection.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectMotorboat.MovementStrategy; +namespace ProjectMotorboat.MovementStrategy; public enum MovementDirection { diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/ObjectParameters.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/ObjectParameters.cs index 2393d1a..254e951 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/ObjectParameters.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/ObjectParameters.cs @@ -1,5 +1,4 @@ - -namespace ProjectMotorboat.MovementStrategy; +namespace ProjectMotorboat.MovementStrategy; public class ObjectParameters { diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/StrategyStatus.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/StrategyStatus.cs index 94acac8..85a9fc8 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/StrategyStatus.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/StrategyStatus.cs @@ -1,4 +1,5 @@ -namespace ProjectMotorboat.MovementStrategy; + +namespace ProjectMotorboat.MovementStrategy; public enum StrategyStatus { diff --git a/ProjectMotorboat/ProjectMotorboat/Program.cs b/ProjectMotorboat/ProjectMotorboat/Program.cs index 2bbdd34..35730ce 100644 --- a/ProjectMotorboat/ProjectMotorboat/Program.cs +++ b/ProjectMotorboat/ProjectMotorboat/Program.cs @@ -1,15 +1,43 @@ -namespace ProjectMotorboat +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + +namespace ProjectMotorboat; + +internal static class Program { - internal static class Program + [STAThread] + static void Main() { - - [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 FormBoatCollection()); + 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/ProjectMotorboat/ProjectMotorboat/ProjectMotorboat.csproj b/ProjectMotorboat/ProjectMotorboat/ProjectMotorboat.csproj index 663fdb8..83076f6 100644 --- a/ProjectMotorboat/ProjectMotorboat/ProjectMotorboat.csproj +++ b/ProjectMotorboat/ProjectMotorboat/ProjectMotorboat.csproj @@ -8,4 +8,19 @@ enable + + + + + + + + + + + + Always + + + \ No newline at end of file diff --git a/ProjectMotorboat/ProjectMotorboat/serilogConfig.json b/ProjectMotorboat/ProjectMotorboat/serilogConfig.json new file mode 100644 index 0000000..9a6ec38 --- /dev/null +++ b/ProjectMotorboat/ProjectMotorboat/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": "Motorboat" + } + } +}