diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs index 9b46b13..c85a5ef 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectSeaplane.CollectionGenericObjects; +using ProjectSeaplane.Exceptions; + +namespace ProjectSeaplane.CollectionGenericObjects; public class ListGenericObjects : ICollectionGenericObjects where T : class @@ -33,26 +35,26 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } public int Insert(T obj) { - if (Count == _maxCount) return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; } public int Insert(T obj, int position) { - if (Count == _maxCount) return -1; - if (position >= Count || position < 0) return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); return position; } public T Remove(int position) { - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); T obj = _collection[position]; _collection.RemoveAt(position); return obj; diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs index e0d0a69..7ee8e66 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectSeaplane.CollectionGenericObjects; +using ProjectSeaplane.Exceptions; + +namespace ProjectSeaplane.CollectionGenericObjects; public class MassiveGenericObjects : ICollectionGenericObjects where T : class @@ -36,9 +38,10 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection = Array.Empty(); } - public T? Get(int position) + public T Get(int position) { - if (position >= _collection.Length || position < 0) return null; + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + //if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } @@ -54,12 +57,11 @@ public class MassiveGenericObjects : ICollectionGenericObjects } ++index; } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - if (position >= _collection.Length || position < 0) - return -1; + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) { _collection[position] = obj; @@ -85,12 +87,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects } --index; } - return -1; + throw new CollectionOverflowException(Count); } public T Remove(int position) { - if (position >= _collection.Length || position < 0) - return null; + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); T obj = _collection[position]; _collection[position] = null; return obj; diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/PlaneSharingService.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/PlaneSharingService.cs index ef049f2..f3bcb30 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/PlaneSharingService.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/PlaneSharingService.cs @@ -32,11 +32,12 @@ internal class PlaneSharingService : AbstractCompany for (int i = 0; i < (_collection?.Count ?? 0); i++) { - if (_collection.Get(i) != null) + try { - _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); - _collection.Get(i).SetPosition(_placeSizeWidth * curWidth, curHeight * _placeSizeHeight + 4); + _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(i)?.SetPosition(_placeSizeWidth * curWidth, curHeight * _placeSizeHeight + 4); } + catch (Exception) { } if (curWidth > 0) curWidth--; else diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs index 6b80720..933e9dc 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectSeaplane.Drawings; +using ProjectSeaplane.Exceptions; using System.Text; namespace ProjectSeaplane.CollectionGenericObjects; @@ -78,11 +79,11 @@ public class StorageCollection /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) { @@ -119,8 +120,6 @@ public class StorageCollection } } - - return true; } /// @@ -128,22 +127,22 @@ public class StorageCollection /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } using (StreamReader fs = File.OpenText(filename)) { string str = fs.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new Exception("В файле нет данных"); } if (!str.StartsWith(_collectionKey)) { - return false; + throw new Exception("В файле неверные данные"); } _storages.Clear(); string strs = ""; @@ -158,23 +157,29 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningPlane() is T ship) + if (elem?.CreateDrawningPlane() is T plane) { - if (collection.Insert(ship) == -1) + try { - return false; + if (collection.Insert(plane) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } } _storages.Add(record[0], collection); } - return true; } } diff --git a/ProjectSeaplane/ProjectSeaplane/Drawings/DrawingPlane.cs b/ProjectSeaplane/ProjectSeaplane/Drawings/DrawingPlane.cs index b6fbb76..6d98967 100644 --- a/ProjectSeaplane/ProjectSeaplane/Drawings/DrawingPlane.cs +++ b/ProjectSeaplane/ProjectSeaplane/Drawings/DrawingPlane.cs @@ -49,9 +49,9 @@ public class DrawingPlane _drawingPlaneHeight = drawingSeaplaneHeight; } - public DrawingPlane(EntityPlane ship) : this() + public DrawingPlane(EntityPlane plane) : this() { - EntityPlane = new EntityPlane(ship.Speed, ship.Weight, ship.BodyColor); + EntityPlane = new EntityPlane(plane.Speed, plane.Weight, plane.BodyColor); } public bool SetPictureSize(int width, int height) diff --git a/ProjectSeaplane/ProjectSeaplane/Drawings/DrawingSeaplane.cs b/ProjectSeaplane/ProjectSeaplane/Drawings/DrawingSeaplane.cs index a2ea5ce..1f15028 100644 --- a/ProjectSeaplane/ProjectSeaplane/Drawings/DrawingSeaplane.cs +++ b/ProjectSeaplane/ProjectSeaplane/Drawings/DrawingSeaplane.cs @@ -14,9 +14,9 @@ public class DrawingSeaplane : DrawingPlane EntityPlane = new EntitySeaplane(speed, weight, bodyColor, additionalColor, floats, inflatableBoat); } - public DrawingSeaplane(EntitySeaplane ship) : base(190, 85) + public DrawingSeaplane(EntitySeaplane plane) : base(190, 85) { - EntityPlane = new EntitySeaplane(ship.Speed, ship.Weight, ship.BodyColor, ship.AdditionalColor, ship.Floats, ship.InflatableBoat); + EntityPlane = new EntitySeaplane(plane.Speed, plane.Weight, plane.BodyColor, plane.AdditionalColor, plane.Floats, plane.InflatableBoat); } public override void DrawTransport(Graphics g) diff --git a/ProjectSeaplane/ProjectSeaplane/Exceptions/CollectionOverflowException.cs b/ProjectSeaplane/ProjectSeaplane/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..19a8c83 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Exceptions/CollectionOverflowException.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 ProjectSeaplane.Exceptions; + +[Serializable] +internal class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { } + public CollectionOverflowException() : base() { } + public CollectionOverflowException(string message) : base(message) { } + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/ProjectSeaplane/ProjectSeaplane/Exceptions/ObjectNotFoundException.cs b/ProjectSeaplane/ProjectSeaplane/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..ef28304 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Exceptions/ObjectNotFoundException.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 ProjectSeaplane.Exceptions; + +[Serializable] +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + public ObjectNotFoundException() : base() { } + public ObjectNotFoundException(string message) : base(message) { } + public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { } + protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Exceptions/PositionOutOfCollectionException.cs b/ProjectSeaplane/ProjectSeaplane/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..a2ab792 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Exceptions/PositionOutOfCollectionException.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 ProjectSeaplane.Exceptions; + +[Serializable] +internal class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { } + public PositionOutOfCollectionException() : base() { } + public PositionOutOfCollectionException(string message) : base(message) { } + public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } + protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/FormSeaplaneCollection.Designer.cs b/ProjectSeaplane/ProjectSeaplane/FormSeaplaneCollection.Designer.cs index 3b3f14a..7f4eaf5 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormSeaplaneCollection.Designer.cs +++ b/ProjectSeaplane/ProjectSeaplane/FormSeaplaneCollection.Designer.cs @@ -66,9 +66,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(764, 24); + groupBoxTools.Location = new Point(677, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(200, 603); + groupBoxTools.Size = new Size(200, 583); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -98,7 +98,7 @@ // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(3, 97); + maskedTextBoxPosition.Location = new Point(3, 50); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(182, 23); @@ -107,7 +107,7 @@ // // buttonRefresh // - buttonRefresh.Location = new Point(3, 216); + buttonRefresh.Location = new Point(3, 197); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(182, 41); buttonRefresh.TabIndex = 6; @@ -117,7 +117,7 @@ // // buttonDelPlane // - buttonDelPlane.Location = new Point(3, 126); + buttonDelPlane.Location = new Point(3, 107); buttonDelPlane.Name = "buttonDelPlane"; buttonDelPlane.Size = new Size(182, 41); buttonDelPlane.TabIndex = 4; @@ -127,7 +127,7 @@ // // buttonGoToCheck // - buttonGoToCheck.Location = new Point(3, 173); + buttonGoToCheck.Location = new Point(3, 154); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(182, 41); buttonGoToCheck.TabIndex = 5; @@ -244,7 +244,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(764, 603); + pictureBox.Size = new Size(677, 583); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -253,7 +253,7 @@ menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(964, 24); + menuStrip.Size = new Size(877, 24); menuStrip.TabIndex = 2; menuStrip.Text = "menuStrip1"; // @@ -292,7 +292,7 @@ // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(964, 627); + ClientSize = new Size(877, 607); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); diff --git a/ProjectSeaplane/ProjectSeaplane/FormSeaplaneCollection.cs b/ProjectSeaplane/ProjectSeaplane/FormSeaplaneCollection.cs index 342e215..9472a99 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormSeaplaneCollection.cs +++ b/ProjectSeaplane/ProjectSeaplane/FormSeaplaneCollection.cs @@ -1,5 +1,7 @@ -using ProjectSeaplane.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectSeaplane.CollectionGenericObjects; using ProjectSeaplane.Drawings; +using ProjectSeaplane.Exceptions; using System.Windows.Forms; namespace ProjectSeaplane; @@ -10,10 +12,14 @@ public partial class FormSeaplaneCollection : Form private AbstractCompany? _company = null; - public FormSeaplaneCollection() + private readonly ILogger _logger; + + public FormSeaplaneCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) @@ -30,67 +36,27 @@ public partial class FormSeaplaneCollection : Form private void SetPlane(DrawingPlane? plane) { - if (_company == null || plane == null) + try { - return; - } - if (_company + plane != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } - } - - private void CreateObject(string type) - { - if (_company == null) - { - return; - } - - Random random = new(); - DrawingPlane drawningPlane; - switch (type) - { - case nameof(DrawingPlane): - drawningPlane = new DrawingPlane(random.Next(100, 300), random.Next(1000, 3000), GetColor(random)); - break; - case nameof(DrawingSeaplane): - drawningPlane = new DrawingSeaplane(random.Next(100, 300), random.Next(1000, 3000), - GetColor(random), GetColor(random), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); - break; - default: + if (_company == null || plane == null) + { return; + } + if (_company + plane != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + plane.GetDataForSave()); + } } - - if (_company + drawningPlane != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else + catch (ObjectNotFoundException) { } + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } - private static Color GetColor(Random random) - { - Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); - ColorDialog dialog = new(); - if (dialog.ShowDialog() == DialogResult.OK) - { - color = dialog.Color; - } - - return color; - } - private void buttonDelPlane_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) @@ -104,14 +70,19 @@ public partial class FormSeaplaneCollection : Form } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удален объект по позиции " + pos); + } } - else + catch (Exception ex) { MessageBox.Show("Не удалось удалить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -124,26 +95,27 @@ public partial class FormSeaplaneCollection : Form DrawingPlane? plane = null; int counter = 100; - while (plane == null) + try { - plane = _company.GetRandomObject(); - counter--; - if (counter <= 0) + while (plane == null) { - break; + plane = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } + FormSeaplane form = new() + { + SetPlane = plane + }; + form.ShowDialog(); } - - if (plane == null) + catch (Exception ex) { - return; + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - - FormSeaplane form = new() - { - SetPlane = plane - }; - form.ShowDialog(); } private void buttonRefresh_Click(object sender, EventArgs e) @@ -164,18 +136,25 @@ public partial class FormSeaplaneCollection : Form return; } - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) + try { - collectionType = CollectionType.Massive; + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); } - else if (radioButtonList.Checked) + catch (Exception ex) { - collectionType = CollectionType.List; + _logger.LogError("Ошибка: {Message}", ex.Message); } - - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); } private void buttonCollectionDel_Click(object sender, EventArgs e) @@ -185,12 +164,20 @@ public partial class FormSeaplaneCollection : Form MessageBox.Show("Коллекция не выбрана"); return; } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + try { - return; + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + return; + } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); + } + catch (Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); } private void RerfreshListBoxItems() @@ -204,7 +191,6 @@ public partial class FormSeaplaneCollection : Form listBoxCollection.Items.Add(colName); } } - } private void buttonCreateCompany_Click(object sender, EventArgs e) @@ -237,15 +223,16 @@ public partial class FormSeaplaneCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storageCollection.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -254,16 +241,17 @@ public partial class FormSeaplaneCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storageCollection.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); RerfreshListBoxItems(); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/ProjectSeaplane/ProjectSeaplane/FormSeaplaneCollection.resx b/ProjectSeaplane/ProjectSeaplane/FormSeaplaneCollection.resx index 7dc5378..a9eb8c9 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormSeaplaneCollection.resx +++ b/ProjectSeaplane/ProjectSeaplane/FormSeaplaneCollection.resx @@ -126,4 +126,7 @@ 255, 17 + + 25 + \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Program.cs b/ProjectSeaplane/ProjectSeaplane/Program.cs index 0405d27..881f886 100644 --- a/ProjectSeaplane/ProjectSeaplane/Program.cs +++ b/ProjectSeaplane/ProjectSeaplane/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using Microsoft.Extensions.Configuration; + namespace ProjectSeaplane { internal static class Program @@ -11,7 +16,31 @@ namespace ProjectSeaplane // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormSeaplaneCollection()); + + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + private static void ConfigureServices(ServiceCollection services) + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder() + .AddJsonFile($"{pathNeed}serilog.json") + .Build()) + .CreateLogger()); + }); } } } \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/ProjectSeaplane.csproj b/ProjectSeaplane/ProjectSeaplane/ProjectSeaplane.csproj index 244387d..57e68f6 100644 --- a/ProjectSeaplane/ProjectSeaplane/ProjectSeaplane.csproj +++ b/ProjectSeaplane/ProjectSeaplane/ProjectSeaplane.csproj @@ -8,6 +8,17 @@ enable + + + + + + + + + + + True diff --git a/ProjectSeaplane/ProjectSeaplane/serilog.json b/ProjectSeaplane/ProjectSeaplane/serilog.json new file mode 100644 index 0000000..d1428e1 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/serilog.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "log.log" } + } + ], + "Properties": { + "Application": "Sample" + } + } +}