diff --git a/Lab1ContainersShip/Lab1ContainersShip/FormShipCollection.cs b/Lab1ContainersShip/Lab1ContainersShip/FormShipCollection.cs index 4015943..dad6c6f 100644 --- a/Lab1ContainersShip/Lab1ContainersShip/FormShipCollection.cs +++ b/Lab1ContainersShip/Lab1ContainersShip/FormShipCollection.cs @@ -1,5 +1,6 @@ using Lab1ContainersShip.DrawingObjects; using Lab1ContainersShip.MovementStrategy; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel; @@ -9,16 +10,19 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using System.Xml.Linq; namespace Lab1ContainersShip { public partial class FormShipCollection : Form { private readonly ShipGenericStorage _storage; - public FormShipCollection() + private readonly ILogger _logger; + public FormShipCollection(ILogger logger) { InitializeComponent(); _storage = new ShipGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } private void FormShipCollection_Load(object sender, EventArgs e) @@ -48,10 +52,13 @@ namespace Lab1ContainersShip { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Пустое название набора"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: { textBoxStorageName.Text} "); + } private void ListBoxObjects_SelectedIndexChanged(object sender,EventArgs e) { @@ -88,19 +95,26 @@ namespace Lab1ContainersShip var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { + _logger.LogWarning("Добавление пустого объекта"); return; } - - if ((obj + drawningShip) != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowShips(); + _ = obj + drawningShip; + + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowShips(); + _logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}"); + + } - else + catch (ApplicationException ex) { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); } - + } private void ButtonRemoveCar_Click(object sender, EventArgs e) @@ -121,14 +135,23 @@ namespace Lab1ContainersShip return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowShips(); + if (obj - pos) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowShips(); + _logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}"); + } } - else + catch (ShipNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); } } @@ -139,8 +162,7 @@ namespace Lab1ContainersShip { return; } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { return; @@ -160,6 +182,7 @@ namespace Lab1ContainersShip _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); ReloadObjects(); + _logger.LogInformation($"Удален набор: {listBoxStorages.SelectedItem}"); } } @@ -167,7 +190,7 @@ namespace Lab1ContainersShip { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + /*if (_storage.SaveData(saveFileDialog.FileName)) { MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); @@ -176,6 +199,17 @@ namespace Lab1ContainersShip { MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + }*/ + try + { + _storage.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName}"); + } + catch (Exception ex) + { + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}"); } } } @@ -184,7 +218,7 @@ namespace Lab1ContainersShip { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + /*if (_storage.LoadData(openFileDialog.FileName)) { ReloadObjects(); MessageBox.Show("Загрузка прошла успешно", @@ -194,8 +228,22 @@ namespace Lab1ContainersShip { MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + }*/ + try + { + _storage.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}"); + } + catch (Exception ex) + { + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}"); } } + ReloadObjects(); } } } diff --git a/Lab1ContainersShip/Lab1ContainersShip/Lab1ContainersShip.csproj b/Lab1ContainersShip/Lab1ContainersShip/Lab1ContainersShip.csproj index 43d2678..a7f6afb 100644 --- a/Lab1ContainersShip/Lab1ContainersShip/Lab1ContainersShip.csproj +++ b/Lab1ContainersShip/Lab1ContainersShip/Lab1ContainersShip.csproj @@ -8,9 +8,26 @@ + + + + + + + + + + + + + + + Always + + \ No newline at end of file diff --git a/Lab1ContainersShip/Lab1ContainersShip/Program.cs b/Lab1ContainersShip/Lab1ContainersShip/Program.cs index bf2ee79..5ee455d 100644 --- a/Lab1ContainersShip/Lab1ContainersShip/Program.cs +++ b/Lab1ContainersShip/Lab1ContainersShip/Program.cs @@ -1,8 +1,18 @@ using System; using System.Collections.Generic; +using System.Drawing; +using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; +using Lab1ContainersShip.Properties; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + + +using Serilog; namespace Lab1ContainersShip { @@ -11,12 +21,52 @@ namespace Lab1ContainersShip /// /// Главная точка входа для приложения. /// - [STAThread] + /*[STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormShipCollection()); + }*/ + [STAThread] + static void Main() + { + // To customize application configuration such as set high DPIsettings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + 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 => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + });*/ + 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}appsettings.json", optional: false, reloadOnChange: true).Build(); + var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); + + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger); + }); + + } + } } diff --git a/Lab1ContainersShip/Lab1ContainersShip/SetGeneric.cs b/Lab1ContainersShip/Lab1ContainersShip/SetGeneric.cs index 2d19029..00f4bb3 100644 --- a/Lab1ContainersShip/Lab1ContainersShip/SetGeneric.cs +++ b/Lab1ContainersShip/Lab1ContainersShip/SetGeneric.cs @@ -39,7 +39,9 @@ namespace Lab1ContainersShip // TODO вставка в начало набора if(_places.Count >= _maxCount) { + throw new StorageOverflowException(); return -1; + } else { @@ -65,11 +67,13 @@ namespace Lab1ContainersShip // TODO вставка по позиции if(_places.Count >= _maxCount) { - return false; + // return false; + throw new StorageOverflowException(position); } if(position < 0 || position > _places.Count) { - return false; + throw new ShipNotFoundException(position); + //return false; } if(position == _places.Count) { @@ -91,14 +95,15 @@ namespace Lab1ContainersShip // TODO проверка позиции // TODO удаление объекта из массива, присвоив элементу массива //значение null - if(position < _places.Count && _places.Count < _maxCount) + if(position < _places.Count) { - _places[position] = null; + _places.RemoveAt(position); return true; } else { - return false; + // return false; + throw new ShipNotFoundException(position); } } @@ -133,9 +138,17 @@ namespace Lab1ContainersShip } set - { + { - Insert(value, position); + //Insert(value, position); + try + { + Insert(value, position); + } + catch + { + return; + } } } diff --git a/Lab1ContainersShip/Lab1ContainersShip/ShipGenericStorage.cs b/Lab1ContainersShip/Lab1ContainersShip/ShipGenericStorage.cs index d192c0a..051eed2 100644 --- a/Lab1ContainersShip/Lab1ContainersShip/ShipGenericStorage.cs +++ b/Lab1ContainersShip/Lab1ContainersShip/ShipGenericStorage.cs @@ -111,7 +111,7 @@ DrawningObjectShip>>(); /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при //сохранении данных -public bool SaveData(string filename) +public void SaveData(string filename) { if (File.Exists(filename)) { @@ -130,13 +130,13 @@ public bool SaveData(string filename) } if (data.Length == 0) { - return false; + throw new Exception("Невалиданя операция, нет данных для сохранения"); } using(StreamWriter sr = new StreamWriter(filename)) { sr.Write($"ShipStorage{Environment.NewLine}{data}"); } - return true; + return; } /// /// Загрузка информации по автомобилям в хранилище из файла @@ -144,22 +144,23 @@ public bool SaveData(string filename) /// Путь и имя файла /// 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 str = sr.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new Exception("Нет данных для загрузки"); } if (!str.StartsWith("ShipStorage")) { - return false; + throw new Exception("Неверный формат данных"); + } _shipStorages.Clear(); str = sr.ReadLine(); @@ -179,16 +180,23 @@ public bool SaveData(string filename) elem?.CreateDrawingShip(_separatorForObject, _pictureWidth, _pictureHeight); if (ship != null) { - if (collection + ship == -1) + /*if (collection + ship == -1) { - return false; + throw new Exception("Ошибка добавления в коллекцию"); + }*/ + try + { + int t = collection + ship; + } + catch (ApplicationException ex) + { + throw new Exception($"Ошибка добавления в коллекцию: {ex.Message}"); } } } _shipStorages.Add(record[0], collection); } } - return true; } } diff --git a/Lab1ContainersShip/Lab1ContainersShip/ShipNotFoundException.cs b/Lab1ContainersShip/Lab1ContainersShip/ShipNotFoundException.cs new file mode 100644 index 0000000..41d3f89 --- /dev/null +++ b/Lab1ContainersShip/Lab1ContainersShip/ShipNotFoundException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Lab1ContainersShip +{ + [Serializable] + 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 contex) : base(info, contex) { } + + } +} diff --git a/Lab1ContainersShip/Lab1ContainersShip/StorageOverflowException.cs b/Lab1ContainersShip/Lab1ContainersShip/StorageOverflowException.cs new file mode 100644 index 0000000..7f94db0 --- /dev/null +++ b/Lab1ContainersShip/Lab1ContainersShip/StorageOverflowException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Lab1ContainersShip +{ + [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) { } + + } +} diff --git a/Lab1ContainersShip/Lab1ContainersShip/appsettings.json b/Lab1ContainersShip/Lab1ContainersShip/appsettings.json new file mode 100644 index 0000000..f9cc1f8 --- /dev/null +++ b/Lab1ContainersShip/Lab1ContainersShip/appsettings.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": "ContainerShip" + } + } + } \ No newline at end of file diff --git a/Lab1ContainersShip/Lab1ContainersShip/nlog.config b/Lab1ContainersShip/Lab1ContainersShip/nlog.config new file mode 100644 index 0000000..54e4ba6 --- /dev/null +++ b/Lab1ContainersShip/Lab1ContainersShip/nlog.config @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file