diff --git a/AntiAirCraftGun/AntiAirCraftGun/AntiAirCraftGun.csproj b/AntiAirCraftGun/AntiAirCraftGun/AntiAirCraftGun.csproj index 13ee123..6e497f5 100644 --- a/AntiAirCraftGun/AntiAirCraftGun/AntiAirCraftGun.csproj +++ b/AntiAirCraftGun/AntiAirCraftGun/AntiAirCraftGun.csproj @@ -8,6 +8,16 @@ enable + + + + + + + + + + True diff --git a/AntiAirCraftGun/AntiAirCraftGun/Exceptions/AntiAirCraftGunNotFoundException.cs b/AntiAirCraftGun/AntiAirCraftGun/Exceptions/AntiAirCraftGunNotFoundException.cs new file mode 100644 index 0000000..83b5e2d --- /dev/null +++ b/AntiAirCraftGun/AntiAirCraftGun/Exceptions/AntiAirCraftGunNotFoundException.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 AntiAircraftGun.Exceptions +{ + [Serializable] + internal class AntiAirCraftGunNotFoundException : ApplicationException + { + public AntiAirCraftGunNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public AntiAirCraftGunNotFoundException() : base() { } + public AntiAirCraftGunNotFoundException(string message) : base(message) { } + public AntiAirCraftGunNotFoundException(string message, Exception exception) : base(message, exception) { } + protected AntiAirCraftGunNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/AntiAirCraftGun/AntiAirCraftGun/Exceptions/StorageOverflowException.cs b/AntiAirCraftGun/AntiAirCraftGun/Exceptions/StorageOverflowException.cs new file mode 100644 index 0000000..12e1a23 --- /dev/null +++ b/AntiAirCraftGun/AntiAirCraftGun/Exceptions/StorageOverflowException.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 AntiAircraftGun.Exceptions +{ + 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/AntiAirCraftGun/AntiAirCraftGun/FormAntiAirCraftGunCollection.cs b/AntiAirCraftGun/AntiAirCraftGun/FormAntiAirCraftGunCollection.cs index 066dab0..697dead 100644 --- a/AntiAirCraftGun/AntiAirCraftGun/FormAntiAirCraftGunCollection.cs +++ b/AntiAirCraftGun/AntiAirCraftGun/FormAntiAirCraftGunCollection.cs @@ -1,6 +1,8 @@ using AntiAircraftGun.DrawingObjects; +using AntiAircraftGun.Exceptions; using AntiAircraftGun.Generics; using AntiAircraftGun.MovementStrategy; +using Microsoft.VisualBasic.Logging; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,12 +12,16 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Serilog; + + namespace AntiAircraftGun { public partial class FormAntiAirCraftGunCollection : Form { private readonly AntiAirCraftGunGenericStorage _storage; + public FormAntiAirCraftGunCollection() { InitializeComponent(); @@ -59,6 +65,7 @@ namespace AntiAircraftGun } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + Serilog.Log.Information($"Добавлен набор: {textBoxStorageName.Text}"); } /// /// Выбор набора @@ -85,9 +92,10 @@ namespace AntiAircraftGun if (MessageBox.Show($"Удалить объект{ listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() - ?? string.Empty); + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; + _storage.DelSet(name); ReloadObjects(); + Serilog.Log.Information($"Удален набор: {name}"); } } @@ -107,16 +115,19 @@ namespace AntiAircraftGun FormAntiAirCraftGunConfig form = new(); form.Show(); Action? zenitDelegate = new((m) => { - bool q = (obj + m); - if (q) + + try { + bool q = (obj + m); MessageBox.Show("Объект добавлен"); + Serilog.Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height); pictureBoxCollection.Image = obj.ShowZenits(); } - else + catch(StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + Serilog.Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена"); + MessageBox.Show(ex.Message); } }); form.AddEvent(zenitDelegate); @@ -137,15 +148,25 @@ namespace AntiAircraftGun { return; } - int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + + try { + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + var q = obj - pos; MessageBox.Show("Объект удален"); + Serilog.Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}"); pictureBoxCollection.Image = obj.ShowZenits(); + } - else + catch(AntiAirCraftGunNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + Serilog.Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); + MessageBox.Show(ex.Message); + } + catch (FormatException ex) + { + Serilog.Log.Warning($"Было введено не число"); + MessageBox.Show("Введите число"); } } @@ -174,15 +195,16 @@ namespace AntiAircraftGun { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + Serilog.Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен"); } - else + catch(Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + Serilog.Log.Warning($"Не удалось сохранить {saveFileDialog.FileName}"); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -195,19 +217,21 @@ namespace AntiAircraftGun { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + Serilog.Log.Information($"Файл {openFileDialog.FileName} успешно загружен"); foreach (var collection in _storage.Keys) { listBoxStorages.Items.Add(collection); } } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + Serilog.Log.Warning("Не удалось загрузить"); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } } diff --git a/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericCollection.cs b/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericCollection.cs index 35d8926..3a8b97b 100644 --- a/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericCollection.cs +++ b/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericCollection.cs @@ -70,8 +70,7 @@ namespace AntiAircraftGun.Generics public static T? operator -(AntiAirCraftGunGenericCollection collect, int pos) { T? obj = collect._collection.Get(pos); - if (obj != null) - collect._collection.Remove(pos); + collect._collection.Remove(pos); return obj; } diff --git a/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericStorage.cs b/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericStorage.cs index c6bbbec..5859b2b 100644 --- a/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericStorage.cs +++ b/AntiAirCraftGun/AntiAirCraftGun/Generics/AntiAirCraftGunGenericStorage.cs @@ -75,7 +75,7 @@ namespace AntiAircraftGun.Generics public void DelSet(string name) { // TODO: Прописать логику для удаления набора - if (_zenitStorages.ContainsKey(name) == null) + if (!_zenitStorages.ContainsKey(name)) { return; } @@ -127,7 +127,7 @@ namespace AntiAircraftGun.Generics } if (data.Length == 0) { - return false; + throw new Exception("Невалидная операция, нет данных для сохранения"); } string toWrite = $"CarStorage{Environment.NewLine}{data}"; var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); @@ -149,7 +149,7 @@ namespace AntiAircraftGun.Generics { if (!File.Exists(filename)) { - return false; + throw new IOException("Файл не найден"); } using (StreamReader sr = new(filename)) { @@ -157,11 +157,11 @@ namespace AntiAircraftGun.Generics var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { - return false; + throw new IOException("Нет данных для загрузки"); } if (!strs[0].StartsWith("CarStorage")) { - return false; + throw new IOException("Неверный формат данных"); } _zenitStorages.Clear(); do @@ -182,7 +182,7 @@ namespace AntiAircraftGun.Generics { if (!(collection + zenit)) { - return false; + throw new Exception("Ошибка добавления в коллекцию"); } } } @@ -192,7 +192,7 @@ namespace AntiAircraftGun.Generics } while (str != null); } return true; - } + } } } \ No newline at end of file diff --git a/AntiAirCraftGun/AntiAirCraftGun/Generics/SetGeneric.cs b/AntiAirCraftGun/AntiAirCraftGun/Generics/SetGeneric.cs index abcfa88..3e42168 100644 --- a/AntiAirCraftGun/AntiAirCraftGun/Generics/SetGeneric.cs +++ b/AntiAirCraftGun/AntiAirCraftGun/Generics/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using AntiAircraftGun.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -38,16 +39,18 @@ namespace AntiAircraftGun.Generics public bool Insert(T car) { if (_places.Count == _maxCount) - return false; + throw new StorageOverflowException(_maxCount); Insert(car, 0); return true; } public bool Insert(T car, int position) { - if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) + if (_places.Count == _maxCount) + throw new StorageOverflowException(_maxCount); + if (!(position >= 0 && position <= Count)) return false; - _places.Insert(position, car); + _places.Insert(position, car); return true; } @@ -60,9 +63,9 @@ namespace AntiAircraftGun.Generics { // Проверка позиции if (position < 0 || position >= Count) - return false; + throw new AntiAirCraftGunNotFoundException(position); + - _places.RemoveAt(position); return true; } diff --git a/AntiAirCraftGun/AntiAirCraftGun/Logger.cs b/AntiAirCraftGun/AntiAirCraftGun/Logger.cs new file mode 100644 index 0000000..5207e32 --- /dev/null +++ b/AntiAirCraftGun/AntiAirCraftGun/Logger.cs @@ -0,0 +1,15 @@ +using Serilog; + +namespace AntiAircraftGun +{ + public static class Logger + { + public static void ConfigureLogger() + { + Log.Logger = new LoggerConfiguration() + .WriteTo.File("log.txt") + .MinimumLevel.Debug() + .CreateLogger(); + } + } +} diff --git a/AntiAirCraftGun/AntiAirCraftGun/Program.cs b/AntiAirCraftGun/AntiAirCraftGun/Program.cs index 45c0534..d6cca64 100644 --- a/AntiAirCraftGun/AntiAirCraftGun/Program.cs +++ b/AntiAirCraftGun/AntiAirCraftGun/Program.cs @@ -1,3 +1,5 @@ +using Microsoft.Extensions.Configuration; +using Serilog; namespace AntiAircraftGun { internal static class Program @@ -8,9 +10,11 @@ namespace AntiAircraftGun [STAThread] static void Main() { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); + + Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder().AddJsonFile("serilog.json").Build()) + .CreateLogger(); + ApplicationConfiguration.Initialize(); Application.Run(new FormAntiAirCraftGunCollection()); } }