diff --git a/AircraftCarrier/AircraftCarrier/AircraftCarrier.csproj b/AircraftCarrier/AircraftCarrier/AircraftCarrier.csproj index 13ee123..3ddff53 100644 --- a/AircraftCarrier/AircraftCarrier/AircraftCarrier.csproj +++ b/AircraftCarrier/AircraftCarrier/AircraftCarrier.csproj @@ -8,6 +8,16 @@ enable + + + + + + + + + + True diff --git a/AircraftCarrier/AircraftCarrier/AircraftNotFoundException.cs b/AircraftCarrier/AircraftCarrier/AircraftNotFoundException.cs new file mode 100644 index 0000000..f7f7b18 --- /dev/null +++ b/AircraftCarrier/AircraftCarrier/AircraftNotFoundException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace AircraftCarrier.Exceptions +{ + [Serializable] + internal class AircraftNotFoundException : ApplicationException + { + public AircraftNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public AircraftNotFoundException() : base() { } + public AircraftNotFoundException(string message) : base(message) { } + public AircraftNotFoundException(string message, Exception exception) : + base(message, exception) + { } + protected AircraftNotFoundException(SerializationInfo info, + StreamingContext contex) : base(info, contex) { } + } +} diff --git a/AircraftCarrier/AircraftCarrier/AircraftsGenericStorage.cs b/AircraftCarrier/AircraftCarrier/AircraftsGenericStorage.cs index d47e98a..14b75d3 100644 --- a/AircraftCarrier/AircraftCarrier/AircraftsGenericStorage.cs +++ b/AircraftCarrier/AircraftCarrier/AircraftsGenericStorage.cs @@ -64,7 +64,7 @@ namespace AircraftCarrier.Generics } } /// Сохранение информации по автомобилям в хранилище в файл - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -83,56 +83,69 @@ namespace AircraftCarrier.Generics } if (data.Length == 0) { - return false; + throw new Exception("Невалиданя операция, нет данных для сохранения"); } - using StreamWriter sw = new(filename); - sw.Write($"AircraftStorage{Environment.NewLine}{data}"); - return true; + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new + UTF8Encoding(true).GetBytes($"CarStorage{Environment.NewLine}{data}"); + fs.Write(info, 0, info.Length); + return; } /// Загрузка информации по автомобилям в хранилище из файла - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } - using (StreamReader sr = new(filename)) + string bufferTextFromFile = ""; + using (FileStream fs = new(filename, FileMode.Open)) { - string str = sr.ReadLine(); - if (str == null || str.Length == 0) + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new(true); + while (fs.Read(b, 0, b.Length) > 0) { - return false; + bufferTextFromFile += temp.GetString(b); } - if (!str.StartsWith("AircraftStorage")) + } + var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, + StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) + { + throw new FileNotFoundException("Нет данных для загрузки"); + } + if (!strs[0].StartsWith("CarStorage")) + { + //если нет такой записи, то это не те данные + throw new FileNotFoundException("Неверный формат данных"); + } + _AircraftStorages.Clear(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) { - //если нет такой записи, то это не те данные - return false; + continue; } - _AircraftStorages.Clear(); - while ((str = sr.ReadLine()) != null) + AircraftsGenericCollection + collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords,StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) { - string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 2) + DrawningAircraft? aircraft = + elem?.CreateDrawningAircraft(_separatorForObject, _pictureWidth, _pictureHeight); + if (aircraft != null) { - continue; - } - AircraftsGenericCollection collection = new(_pictureWidth, _pictureHeight); - string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set.Reverse()) - { - DrawningAircraft? aircraft = elem?.CreateDrawningAircraft(_separatorForObject, _pictureWidth, _pictureHeight); - if (aircraft != null) + if (collection + aircraft == -1) { - if (collection + aircraft == -1) - { - return false; - } + throw new ApplicationException("Ошибка добавления в коллекцию"); } } - _AircraftStorages.Add(record[0], collection); } + _AircraftStorages.Add(record[0], collection); } - return true; + } } } diff --git a/AircraftCarrier/AircraftCarrier/AppSettings.json b/AircraftCarrier/AircraftCarrier/AppSettings.json new file mode 100644 index 0000000..ee1e253 --- /dev/null +++ b/AircraftCarrier/AircraftCarrier/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": "Aircraft" + } + } +} \ No newline at end of file diff --git a/AircraftCarrier/AircraftCarrier/FormAircraftCollection.cs b/AircraftCarrier/AircraftCarrier/FormAircraftCollection.cs index 366c969..a3f61ac 100644 --- a/AircraftCarrier/AircraftCarrier/FormAircraftCollection.cs +++ b/AircraftCarrier/AircraftCarrier/FormAircraftCollection.cs @@ -10,15 +10,21 @@ using System.Windows.Forms; using AircraftCarrier.DrawningObjects; using AircraftCarrier.Generics; using AircraftCarrier.MovementStrategy; +using Microsoft.Extensions.Logging; +using AircraftCarrier.Exceptions; + namespace AircraftCarrier { public partial class FormAircraftCollection : Form { private readonly AircraftsGenericStorage _storage; - public FormAircraftCollection() + private readonly ILogger _logger; + public FormAircraftCollection(ILogger logger) { InitializeComponent(); - _storage = new AircraftsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _storage = new AircraftsGenericStorage(pictureBoxCollection.Width, + pictureBoxCollection.Height); + _logger = logger; } /// Заполнение listBoxObjects private void ReloadObjects() @@ -43,10 +49,12 @@ namespace AircraftCarrier if (string.IsNullOrEmpty(textBoxStorageName.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Неудачная попытка добавить набор: заполнены не все данные"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Набор добавлен: {textBoxStorageName.Text}"); } private void listBoxStorage_SelectedIndexChanged(object sender, EventArgs e) { @@ -56,20 +64,23 @@ namespace AircraftCarrier { if (listBoxStorage.SelectedIndex == -1) { + _logger.LogWarning($"Неудачная попытка удалить набор: набор не выбран"); return; } - if (MessageBox.Show($"Удалить объект{listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, - MessageBoxIcon.Question) == DialogResult.Yes) + string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty; + + if (MessageBox.Show($"Удалить набор {name}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorage.SelectedItem.ToString() - ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Удаленный набор: {name}"); } } private void ButtonAddAircraft_Click(object sender, EventArgs e) { if (listBoxStorage.SelectedIndex == -1) { + _logger.LogWarning($"Неудачная попытка добавить объект: набор не выбран"); return; } var formMonorailConfig = new FormAircraftConfig(); @@ -87,44 +98,64 @@ namespace AircraftCarrier var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { + _logger.LogWarning($"Неудачная попытка добавить объект: значение set равно null"); return; } - if (obj + aircraft != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowAircrafts(); + if (obj + aircraft != -1) + { + MessageBox.Show("Добавленный объект"); + pictureBoxCollection.Image = obj.ShowAircrafts(); + _logger.LogInformation($"Добавленный объект {aircraft}"); + } + else + { + MessageBox.Show("Неудачная попытка добавить объект"); + } } - else + catch(ApplicationException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"Неудачная попытка добавить объект: {ex.Message}"); } } private void ButtonRemoveAircraft_Click(object sender, EventArgs e) { if (listBoxStorage.SelectedIndex == -1) { + _logger.LogWarning($"Неудачная попытка удалить объект: набор не выбран"); return; } var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { + _logger.LogWarning($"Неудачная попытка удалить объект: значение set равно 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 != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowAircrafts(); + if (obj - pos) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowAircrafts(); + _logger.LogInformation($"Удаленный объект на месте: {pos}"); + } + else + { + MessageBox.Show("Неудачная попытка удалить объект"); + } } - else + catch (AircraftNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"Неудачная попытка удалить объект: {ex.Message}"); } } private void ButtonRefreshCollection_Click(object sender, EventArgs e) @@ -146,36 +177,41 @@ namespace AircraftCarrier { 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 (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", + 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 (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", + _storage.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - ReloadObjects(); + _logger.LogInformation($"Файл успешно сохранен: {saveFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", + MessageBox.Show($"Сбой загрузки: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось загрузить файл: {ex.Message}"); } } } - } } diff --git a/AircraftCarrier/AircraftCarrier/Program.cs b/AircraftCarrier/AircraftCarrier/Program.cs index a557a9c..39dddc8 100644 --- a/AircraftCarrier/AircraftCarrier/Program.cs +++ b/AircraftCarrier/AircraftCarrier/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace AircraftCarrier { internal static class Program @@ -6,10 +11,32 @@ namespace AircraftCarrier [STAThread] static void Main() { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormAircraftCollection()); + 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}appsettings.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/AircraftCarrier/AircraftCarrier/SetGeneric.cs b/AircraftCarrier/AircraftCarrier/SetGeneric.cs index 006b946..35f5291 100644 --- a/AircraftCarrier/AircraftCarrier/SetGeneric.cs +++ b/AircraftCarrier/AircraftCarrier/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using AircraftCarrier.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -28,8 +29,10 @@ namespace AircraftCarrier.Generics /// Добавление объекта в набор на конкретную позицию public int Insert(T Aircraft, int position) { - if (position < 0 || position > Count || Count >= _maxCount) - return -1; + if (position < 0 || position > Count) + throw new AircraftNotFoundException("Impossible to insert"); + if (Count >= _maxCount) + throw new StorageOverflowException(_maxCount); _places.Insert(position, Aircraft); return position; @@ -38,7 +41,7 @@ namespace AircraftCarrier.Generics public bool Remove(int position) { if (position < 0 || position >= Count) - return false; + throw new AircraftNotFoundException(position); _places.RemoveAt(position); return true; } diff --git a/AircraftCarrier/AircraftCarrier/StorageOverflowException.cs b/AircraftCarrier/AircraftCarrier/StorageOverflowException.cs new file mode 100644 index 0000000..a457686 --- /dev/null +++ b/AircraftCarrier/AircraftCarrier/StorageOverflowException.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 AircraftCarrier +{ + [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) { } + } +}