diff --git a/ContainerShip/ContainerShip.csproj b/ContainerShip/ContainerShip.csproj index 13ee123..7f13740 100644 --- a/ContainerShip/ContainerShip.csproj +++ b/ContainerShip/ContainerShip.csproj @@ -8,6 +8,17 @@ enable + + + + + + + + + + + True diff --git a/ContainerShip/FormShipCollection.cs b/ContainerShip/FormShipCollection.cs index eaf7727..831f3f8 100644 --- a/ContainerShip/FormShipCollection.cs +++ b/ContainerShip/FormShipCollection.cs @@ -8,19 +8,25 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using ContainerShip.MovementStrategy; +using System.Xml.Linq; +using Microsoft.Extensions.Logging; using ContainerShip.DrawningObjects; using ContainerShip.Generic; +using ContainerShip.Exceptions; + namespace ContainerShip { public partial class FormShipCollection : Form { private readonly ShipsGenericStorage _storage; + private readonly ILogger _logger; - public FormShipCollection() + public FormShipCollection(ILogger logger) { InitializeComponent(); _storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } private void ReloadObjects() { @@ -43,12 +49,12 @@ namespace ContainerShip { if (string.IsNullOrEmpty(textBoxStorageName.Text)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e) { @@ -60,10 +66,12 @@ namespace ContainerShip { 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); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Удалён набор: {name}"); } } @@ -75,7 +83,7 @@ namespace ContainerShip } - private void AddShip(DrawningShip selectedShip) + private void AddShip(DrawningShip _ship) { if (listBoxStorages.SelectedIndex == -1) { @@ -87,15 +95,24 @@ namespace ContainerShip { return; } - selectedShip.ChangeBordersPicture(pictureBoxCollection.Width, pictureBoxCollection.Height); - if (obj + selectedShip != -1) + _ship.ChangeBordersPicture(Width, Height); + try { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowShips(); + if (obj + _ship != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowShips(); + _logger.LogInformation($"Добавлен объект: {_ship.EntityShip.BodyColor}"); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning(ex.Message); } } @@ -105,29 +122,42 @@ namespace ContainerShip { 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) { return; } - int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowShips(); + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + if (obj - pos) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowShips(); + _logger.LogInformation($"Удалён объект по позиции : {pos}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (FormatException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show("Неверный формат ввода"); + _logger.LogWarning("Неверный формат ввода"); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning(ex.Message); } } + private void buttonUpdate_Click(object sender, EventArgs e) { if (listBoxStorages.SelectedIndex == -1) @@ -142,36 +172,43 @@ namespace ContainerShip } pictureBoxCollection.Image = obj.ShowShips(); } + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Файл сохранён по пути: {saveFileDialog.FileName}"); } - else + catch (InvalidOperationException ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning(ex.Message); } } } + private void LoadToolStripMenuItem_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - ReloadObjects(); - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; - pictureBoxCollection.Image = obj.ShowShips(); + _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Файл загружен по пути: {openFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning(ex.Message); } } + ReloadObjects(); } + } } diff --git a/ContainerShip/FormShips.cs b/ContainerShip/FormShips.cs index 2a10433..e12d0cb 100644 --- a/ContainerShip/FormShips.cs +++ b/ContainerShip/FormShips.cs @@ -6,7 +6,15 @@ namespace ContainerShip public partial class FormShips : Form { private DrawningShip? _drawningShip; + + /// + /// + /// private AbstractStrategy? _abstractStrategy; + + /// + /// + /// public DrawningShip? SelectedShip { get; private set; } public FormShips() @@ -27,10 +35,17 @@ namespace ContainerShip _drawningShip.DrawTransport(gr); pictureBoxShips.Image = bmp; } + + /// + /// " " + /// + /// + /// private void ButtonCreateContainerShip_Click(object sender, EventArgs e) { Random random = new Random(); Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); + //TODO ColorDialog dialog = new(); if (dialog.ShowDialog() == DialogResult.OK) { @@ -38,6 +53,7 @@ namespace ContainerShip } Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); + //TODO if (dialog.ShowDialog() == DialogResult.OK) { dopColor = dialog.Color; @@ -50,10 +66,17 @@ namespace ContainerShip _drawningShip.SetPosition(random.Next(10, 200), random.Next(10, 200)); Draw(); } + + /// + /// " " + /// + /// + /// private void ButtonCreateShip_Click(object sender, EventArgs e) { Random random = new(); Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); + //TODO ColorDialog dialog = new(); if (dialog.ShowDialog() == DialogResult.OK) { @@ -90,6 +113,12 @@ namespace ContainerShip } Draw(); } + + /// + /// "" + /// + /// + /// private void ButtonStep_Click(object sender, EventArgs e) { if (_drawningShip == null) @@ -132,6 +161,7 @@ namespace ContainerShip SelectedShip = _drawningShip; DialogResult = DialogResult.OK; } + } } diff --git a/ContainerShip/Program.cs b/ContainerShip/Program.cs index a13bbc1..85a5eed 100644 --- a/ContainerShip/Program.cs +++ b/ContainerShip/Program.cs @@ -1,3 +1,9 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Serilog; + + namespace ContainerShip { internal static class Program @@ -11,7 +17,30 @@ namespace ContainerShip // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormShipCollection()); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + 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}serilog.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/ContainerShip/SetGeneric.cs b/ContainerShip/SetGeneric.cs index 31d7cd3..c2744f8 100644 --- a/ContainerShip/SetGeneric.cs +++ b/ContainerShip/SetGeneric.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using ContainerShip.Exceptions; namespace ContainerShip.Generic { @@ -19,26 +20,28 @@ namespace ContainerShip.Generic } public int Insert(T ship) { - _places.Insert(0, ship); - return 0; + return Insert(ship, 0); } - public bool Insert(T ship, int position) + public int Insert(T ship, int position) { - if (position < 0 || position >= Count || Count >= _maxCount) + if (Count >= _maxCount) { - return false; + throw new StorageOverflowException(_maxCount); + } + if (position < 0 || position >= _maxCount) + { + throw new IndexOutOfRangeException("Индекс вне границ коллекции"); } _places.Insert(position, ship); - return true; + return 0; } public bool Remove(int position) { if (position < 0 || position >= Count) { - return false; + throw new ShipNotFoundException(position); } _places.RemoveAt(position); - return true; } public T? this[int position] diff --git a/ContainerShip/ShipNotFoundException.cs b/ContainerShip/ShipNotFoundException.cs new file mode 100644 index 0000000..4ba27bb --- /dev/null +++ b/ContainerShip/ShipNotFoundException.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 ContainerShip.Exceptions +{ + internal class ShipNotFoundException : ApplicationException + { + public ShipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public ShipNotFoundException() : base() { } + public ShipNotFoundException(string message) : base(message) { } + public ShipNotFoundException(string message, Exception exception) : base(message, exception) { } + protected ShipNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/ContainerShip/ShipsGenericCollection.cs b/ContainerShip/ShipsGenericCollection.cs index 9070132..143062a 100644 --- a/ContainerShip/ShipsGenericCollection.cs +++ b/ContainerShip/ShipsGenericCollection.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using ContainerShip.Generic; using ContainerShip.MovementStrategy; using ContainerShip.DrawningObjects; +using ContainerShip.Exceptions; namespace ContainerShip.Generic { @@ -13,6 +14,7 @@ namespace ContainerShip.Generic where T : DrawningShip where U : IMoveableObject { + public int count => _collection.Count; private readonly int _pictureWidth; private readonly int _pictureHeight; private readonly int _placeSizeWidth = 210; @@ -38,7 +40,7 @@ namespace ContainerShip.Generic { if (collect._collection[pos] == null) { - return false; + throw new ShipNotFoundException(pos); } return collect?._collection.Remove(pos) ?? false; } @@ -78,7 +80,6 @@ namespace ContainerShip.Generic for (int i = 0; i < _collection.Count; i++) { - // TODO получение объекта DrawningShip _ship = _collection[i]; if (_ship != null) { if (x < 0) diff --git a/ContainerShip/ShipsGenericStorage.cs b/ContainerShip/ShipsGenericStorage.cs index 8fb99b5..941dabb 100644 --- a/ContainerShip/ShipsGenericStorage.cs +++ b/ContainerShip/ShipsGenericStorage.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading.Tasks; using ContainerShip.MovementStrategy; using ContainerShip.DrawningObjects; +using ContainerShip.Entities; namespace ContainerShip.Generic { @@ -48,6 +49,11 @@ namespace ContainerShip.Generic } public bool SaveData(string filename) { + if (_shipStorages.Count == 0) + { + throw new InvalidOperationException("Невалидная операция, нет данных для сохранения"); + } + if (File.Exists(filename)) { File.Delete(filename); @@ -56,9 +62,15 @@ namespace ContainerShip.Generic using (StreamWriter sw = File.CreateText(filename)) { sw.WriteLine($"ShipStorage"); + foreach (var record in _shipStorages) { StringBuilder records = new(); + + if (record.Value.count <= 0) + { + throw new InvalidOperationException("Невалидная операция, нет данных для сохранения"); + } foreach (DrawningShip? elem in record.Value.GetShip) { records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); @@ -66,31 +78,40 @@ namespace ContainerShip.Generic sw.WriteLine($"{record.Key}{_separatorForKeyValue}{records}"); } } - return true; } public bool LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException($"Файл {filename} не найден"); } using (StreamReader sr = File.OpenText(filename)) { string? curLine = sr.ReadLine(); - if (curLine == null || !curLine.Contains("ShipStorage")) + if (curLine == null || curLine.Length == 0 || !curLine.StartsWith("ShipStorage")) { - return false; + throw new ArgumentException("Неверный формат данных"); } _shipStorages.Clear(); curLine = sr.ReadLine(); + if (curLine == null || curLine.Length == 0) + { + throw new ArgumentException("Нет данных"); + } while (curLine != null) { + if (!curLine.Contains(_separatorRecords)) + { + throw new ArgumentException("Коллекция пуста"); + } + string[] record = curLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); ShipsGenericCollection collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) @@ -100,7 +121,7 @@ namespace ContainerShip.Generic { if (collection + ship == -1) { - return false; + throw new InvalidOperationException("Невалидная операция, ошибка добавления в коллекцию"); } } } diff --git a/ContainerShip/Status.cs b/ContainerShip/Status.cs index e5f8210..de4c75b 100644 --- a/ContainerShip/Status.cs +++ b/ContainerShip/Status.cs @@ -6,9 +6,6 @@ using System.Threading.Tasks; namespace ContainerShip.MovementStrategy { - /// - /// Статус выполнения операции перемещения - /// public enum Status { NotInit, diff --git a/ContainerShip/StorageOverflowException.cs b/ContainerShip/StorageOverflowException.cs new file mode 100644 index 0000000..99cf02d --- /dev/null +++ b/ContainerShip/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 ContainerShip.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 context) : base(info, context) { } + } +} diff --git a/ContainerShip/serilog.json b/ContainerShip/serilog.json new file mode 100644 index 0000000..9da588d --- /dev/null +++ b/ContainerShip/serilog.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/carlog.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "ContainerShip" + } + } +} \ No newline at end of file