From e2c34a525734b2bc344ba2b2a0ba9846e2f72f2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A2=D0=B0=D0=B1=D0=B5=D0=B5=D0=B2=20=D0=90=D0=BB=D0=B5?= =?UTF-8?q?=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= Date: Tue, 19 Dec 2023 17:48:36 +0400 Subject: [PATCH] =?UTF-8?q?=D0=A1=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=207=20=D0=BB=D0=B0=D0=B1=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AntiAircraftGun/AntiAircraftGun.csproj | 38 +++++++++ .../AircraftGunNotFoundException.cs | 19 +++++ .../Exceptions/StorageOverflowException.cs | 19 +++++ .../FormAircraftGunCollection.Designer.cs | 16 ++-- .../FormAircraftGunCollection.cs | 82 ++++++++++++++----- .../FormAircraftGunCollection.resx | 3 + .../AntiAircraftGunsGenericCollection.cs | 8 +- .../AntiAircraftGunsGenericStorage.cs | 17 ++-- .../AntiAircraftGun/Generics/SetGeneric.cs | 17 ++-- AntiAircraftGun/AntiAircraftGun/Program.cs | 31 ++++++- .../AntiAircraftGun/appsettings.json | 20 +++++ 11 files changed, 216 insertions(+), 54 deletions(-) create mode 100644 AntiAircraftGun/AntiAircraftGun/Exceptions/AircraftGunNotFoundException.cs create mode 100644 AntiAircraftGun/AntiAircraftGun/Exceptions/StorageOverflowException.cs create mode 100644 AntiAircraftGun/AntiAircraftGun/appsettings.json diff --git a/AntiAircraftGun/AntiAircraftGun/AntiAircraftGun.csproj b/AntiAircraftGun/AntiAircraftGun/AntiAircraftGun.csproj index 13ee123..6d2953f 100644 --- a/AntiAircraftGun/AntiAircraftGun/AntiAircraftGun.csproj +++ b/AntiAircraftGun/AntiAircraftGun/AntiAircraftGun.csproj @@ -8,6 +8,38 @@ enable + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + True @@ -23,4 +55,10 @@ + + + Always + + + \ No newline at end of file diff --git a/AntiAircraftGun/AntiAircraftGun/Exceptions/AircraftGunNotFoundException.cs b/AntiAircraftGun/AntiAircraftGun/Exceptions/AircraftGunNotFoundException.cs new file mode 100644 index 0000000..9cd03ea --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/Exceptions/AircraftGunNotFoundException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace AntiAircraftGun.Exceptions +{ + [Serializable] + internal class AircraftGunNotFoundException : ApplicationException + { + public AircraftGunNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public AircraftGunNotFoundException() : base() { } + public AircraftGunNotFoundException(string message) : base(message) { } + public AircraftGunNotFoundException(string message, Exception exception) : base(message, exception) { } + protected AircraftGunNotFoundException(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..fc3dbe5 --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/Exceptions/StorageOverflowException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace AntiAircraftGun.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/AntiAircraftGun/AntiAircraftGun/FormAircraftGunCollection.Designer.cs b/AntiAircraftGun/AntiAircraftGun/FormAircraftGunCollection.Designer.cs index 8987274..c5e271f 100644 --- a/AntiAircraftGun/AntiAircraftGun/FormAircraftGunCollection.Designer.cs +++ b/AntiAircraftGun/AntiAircraftGun/FormAircraftGunCollection.Designer.cs @@ -53,9 +53,9 @@ // // pictureBoxCollection // - this.pictureBoxCollection.Location = new System.Drawing.Point(12, 89); + this.pictureBoxCollection.Location = new System.Drawing.Point(12, 27); this.pictureBoxCollection.Name = "pictureBoxCollection"; - this.pictureBoxCollection.Size = new System.Drawing.Size(634, 354); + this.pictureBoxCollection.Size = new System.Drawing.Size(797, 517); this.pictureBoxCollection.TabIndex = 0; this.pictureBoxCollection.TabStop = false; // @@ -66,7 +66,7 @@ this.groupBox1.Controls.Add(this.ButtonAddAircraftGun); this.groupBox1.Controls.Add(this.ButtonRemoveAircraftGun); this.groupBox1.Controls.Add(this.ButtonRefreshCollection); - this.groupBox1.Location = new System.Drawing.Point(658, 6); + this.groupBox1.Location = new System.Drawing.Point(815, 37); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(236, 437); this.groupBox1.TabIndex = 1; @@ -79,7 +79,7 @@ this.groupBox2.Controls.Add(this.textBoxStorageName); this.groupBox2.Controls.Add(this.ButtonAddObject); this.groupBox2.Controls.Add(this.ButtonDelObject); - this.groupBox2.Location = new System.Drawing.Point(19, 28); + this.groupBox2.Location = new System.Drawing.Point(21, 22); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(209, 222); this.groupBox2.TabIndex = 6; @@ -166,7 +166,7 @@ this.файлToolStripMenuItem}); this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Name = "menuStrip"; - this.menuStrip.Size = new System.Drawing.Size(906, 24); + this.menuStrip.Size = new System.Drawing.Size(1063, 24); this.menuStrip.TabIndex = 2; this.menuStrip.Text = "menuStrip1"; // @@ -182,14 +182,14 @@ // SaveToolStripMenuItem // this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; - this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.SaveToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.SaveToolStripMenuItem.Text = "Сохранение"; this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); // // LoadToolStripMenuItem // this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; - this.LoadToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.LoadToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.LoadToolStripMenuItem.Text = "Загрузка"; this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click); // @@ -206,7 +206,7 @@ // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(906, 450); + this.ClientSize = new System.Drawing.Size(1063, 556); this.Controls.Add(this.groupBox1); this.Controls.Add(this.pictureBoxCollection); this.Controls.Add(this.menuStrip); diff --git a/AntiAircraftGun/AntiAircraftGun/FormAircraftGunCollection.cs b/AntiAircraftGun/AntiAircraftGun/FormAircraftGunCollection.cs index dbd8cc8..38fcb7d 100644 --- a/AntiAircraftGun/AntiAircraftGun/FormAircraftGunCollection.cs +++ b/AntiAircraftGun/AntiAircraftGun/FormAircraftGunCollection.cs @@ -1,4 +1,5 @@ using AntiAircraftGun.DrawningObjects; +using AntiAircraftGun.Exceptions; using AntiAircraftGun.Generics; using AntiAircraftGun.MovementStrategy; using System; @@ -10,17 +11,22 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using System.Xml.Linq; namespace AntiAircraftGun { public partial class FormAircraftGunCollection : Form { private readonly AntiAircraftGunsGenericStorage _storage; - //private readonly AntiAircraftGunsGenericCollection _aircraftguns; - public FormAircraftGunCollection() + + private readonly ILogger _logger; + + public FormAircraftGunCollection(ILogger logger) { InitializeComponent(); _storage = new AntiAircraftGunsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } // Заполнение listBoxObjects private void ReloadObjects() @@ -65,6 +71,7 @@ namespace AntiAircraftGun return; } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? String.Empty]; + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; if (obj == null) { return; @@ -74,15 +81,26 @@ namespace AntiAircraftGun return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удалён"); - pictureBoxCollection.Image = obj.ShowAntiAircraftGuns(); + if (obj - pos != null) + { + MessageBox.Show("Объект удалён"); + pictureBoxCollection.Image = obj.ShowAntiAircraftGuns(); + _logger.LogInformation($"Из набора {name} удален объект"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning("Не удалось удалить объект"); + } } - else + catch(AircraftGunNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message}. Не удалось удалить объект"); } + } private void AddAircraftGun(DrawningAircraftGun aircraftGun) @@ -94,18 +112,29 @@ namespace AntiAircraftGun return; } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; if (obj == null) { return; } - if (obj + aircraftGun) + try { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowAntiAircraftGuns(); + if (obj + aircraftGun) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowAntiAircraftGuns(); + _logger.LogInformation($"В набор {name} добавлен объект"); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning("Не удалось добавить объект"); + } } - else + catch(StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message}. Не удалось добавить объект"); } } // Добавление объекта в набор @@ -130,13 +159,16 @@ namespace AntiAircraftGun { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning($"Удаление невыбранного набора"); return; } - if (MessageBox.Show($"удалить объект {listBoxStorages.SelectedItem}?", "удаление", MessageBoxButtons.YesNo, + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show($"удалить объект {name}?", "удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } @@ -146,10 +178,12 @@ namespace AntiAircraftGun 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 listBoxStorages_SelectedIndexChanged(object sender, EventArgs e) @@ -162,13 +196,15 @@ namespace AntiAircraftGun { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение"); } - else - { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + catch (Exception ex) { + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Ошибка сохранения"); } } } @@ -178,15 +214,17 @@ namespace AntiAircraftGun { if(openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); ReloadObjects(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка"); } - else - { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - } + catch (Exception ex) { + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Ошибка загрузки"); + } } } } diff --git a/AntiAircraftGun/AntiAircraftGun/FormAircraftGunCollection.resx b/AntiAircraftGun/AntiAircraftGun/FormAircraftGunCollection.resx index afb1440..843b196 100644 --- a/AntiAircraftGun/AntiAircraftGun/FormAircraftGunCollection.resx +++ b/AntiAircraftGun/AntiAircraftGun/FormAircraftGunCollection.resx @@ -66,4 +66,7 @@ 272, 18 + + 25 + \ No newline at end of file diff --git a/AntiAircraftGun/AntiAircraftGun/Generics/AntiAircraftGunsGenericCollection.cs b/AntiAircraftGun/AntiAircraftGun/Generics/AntiAircraftGunsGenericCollection.cs index 564e6f4..1996b83 100644 --- a/AntiAircraftGun/AntiAircraftGun/Generics/AntiAircraftGunsGenericCollection.cs +++ b/AntiAircraftGun/AntiAircraftGun/Generics/AntiAircraftGunsGenericCollection.cs @@ -44,15 +44,11 @@ namespace AntiAircraftGun.Generics } // Перегрузка оператора вычитания - public static bool operator -(AntiAircraftGunsGenericCollection collect, int pos) + public static T? operator -(AntiAircraftGunsGenericCollection collect, int pos) { T? obj = collect._collection[pos]; - if (obj == null) - { - return false; - } collect._collection.Remove(pos); - return true; + return obj; } // Получение объекта IMoveableObject diff --git a/AntiAircraftGun/AntiAircraftGun/Generics/AntiAircraftGunsGenericStorage.cs b/AntiAircraftGun/AntiAircraftGun/Generics/AntiAircraftGunsGenericStorage.cs index 54318a6..33c27c1 100644 --- a/AntiAircraftGun/AntiAircraftGun/Generics/AntiAircraftGunsGenericStorage.cs +++ b/AntiAircraftGun/AntiAircraftGun/Generics/AntiAircraftGunsGenericStorage.cs @@ -86,7 +86,7 @@ namespace AntiAircraftGun.Generics } if (data.Length == 0) { - return false; + throw new Exception("Невалидная операция, нет данных для сохранения"); } using StreamWriter fs = new StreamWriter(filename); @@ -100,24 +100,23 @@ namespace AntiAircraftGun.Generics { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } using (StreamReader fs = new StreamReader(filename)) { string str = fs.ReadLine(); + if (str == null || str.Length == 0) + { + throw new NullReferenceException("Нет данных для загрузки"); + } if (!str.StartsWith("AircraftStorage")) { - return false; + throw new FormatException("Неверный формат данных"); } _aircraftgunStorages.Clear(); while ((str = fs.ReadLine()) != null) { - if (str.Length == 0) - { - return false; - } - string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); if (record.Length != 2) { @@ -133,7 +132,7 @@ namespace AntiAircraftGun.Generics { if (!(collection + aircraftgun)) { - return false; + throw new ApplicationException("Ошибка добавления в коллекцию"); } } } diff --git a/AntiAircraftGun/AntiAircraftGun/Generics/SetGeneric.cs b/AntiAircraftGun/AntiAircraftGun/Generics/SetGeneric.cs index 8d8ba6d..6f72744 100644 --- a/AntiAircraftGun/AntiAircraftGun/Generics/SetGeneric.cs +++ b/AntiAircraftGun/AntiAircraftGun/Generics/SetGeneric.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using AntiAircraftGun.Exceptions; namespace AntiAircraftGun.Generics { @@ -39,13 +40,13 @@ namespace AntiAircraftGun.Generics { if (position < 0 || position >= _maxCount) { - return false; + throw new AircraftGunNotFoundException(position); } if (Count >= _maxCount) { - return false; + throw new StorageOverflowException(_maxCount); } - _places.Insert(0, antiaircraftgun); + _places.Insert(position, antiaircraftgun); return true; } @@ -56,11 +57,11 @@ namespace AntiAircraftGun.Generics { return false; } - if (position >= Count) + if (_places[position] == null) { - return false; + throw new AircraftGunNotFoundException(position); } - _places.RemoveAt(position); + _places[position] = null; return true; } @@ -69,7 +70,7 @@ namespace AntiAircraftGun.Generics { get { - if (position < 0 || position >= _maxCount) + if (position < 0 || position >= Count) { return null; } @@ -77,7 +78,7 @@ namespace AntiAircraftGun.Generics } set { - if (position < 0 || position >= _maxCount) + if (position < 0 || position >= Count) { return; } diff --git a/AntiAircraftGun/AntiAircraftGun/Program.cs b/AntiAircraftGun/AntiAircraftGun/Program.cs index 7990f84..413c80e 100644 --- a/AntiAircraftGun/AntiAircraftGun/Program.cs +++ b/AntiAircraftGun/AntiAircraftGun/Program.cs @@ -1,3 +1,11 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using System; +using System.IO; +using System.Windows.Forms; + namespace AntiAircraftGun { internal static class Program @@ -11,7 +19,28 @@ namespace AntiAircraftGun // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormAircraftGunCollection()); + 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 appPath = ""; + for(int i = 0; i < path.Length - 3; i++) + { + appPath += path[i] + "\\"; + } + var configuration = new ConfigurationBuilder().AddJsonFile($"{appPath}appsettings.json").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/AntiAircraftGun/AntiAircraftGun/appsettings.json b/AntiAircraftGun/AntiAircraftGun/appsettings.json new file mode 100644 index 0000000..2a971ad --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/appsettings.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "logs/aircraftgunlog-.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Loco" + } + } +}