From c9945dab89b8661882964b26ae4e656bf1cec5a4 Mon Sep 17 00:00:00 2001 From: RozhVan Date: Sun, 5 May 2024 20:11:54 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 23 ++- .../ListGenericObjects.cs | 25 ++- .../CollectionGenericObjects/Marina.cs | 31 ++-- .../MassiveGenericObjects.cs | 41 +++-- .../StorageCollection.cs | 143 +++++++++--------- .../Exceptions/CollectionOverflowException.cs | 15 ++ .../Exceptions/ObjectNotFoundException.cs | 15 ++ .../PositionOutOfCollectionException.cs | 15 ++ .../FormShipCollection.Designer.cs | 10 +- .../ProjectPlane/FormShipCollection.cs | 78 ++++++---- ProjectPlane/ProjectPlane/Program.cs | 29 +++- ProjectPlane/ProjectPlane/ProjectPlane.csproj | 19 +++ ProjectPlane/ProjectPlane/ShipDelegate.cs | 5 - ProjectPlane/ProjectPlane/log20240505.txt | 35 +++++ ProjectPlane/ProjectPlane/serilogConfig.json | 25 +++ 15 files changed, 361 insertions(+), 148 deletions(-) create mode 100644 ProjectPlane/ProjectPlane/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectPlane/ProjectPlane/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectPlane/ProjectPlane/Exceptions/PositionOutOfCollectionException.cs delete mode 100644 ProjectPlane/ProjectPlane/ShipDelegate.cs create mode 100644 ProjectPlane/ProjectPlane/log20240505.txt create mode 100644 ProjectPlane/ProjectPlane/serilogConfig.json diff --git a/ProjectPlane/ProjectPlane/CollectionGenericObjects/AbstractCompany.cs b/ProjectPlane/ProjectPlane/CollectionGenericObjects/AbstractCompany.cs index bce7e9c..cbe69e2 100644 --- a/ProjectPlane/ProjectPlane/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectPlane/ProjectPlane/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectPlane.Drawnings; +using ProjectPlane.Exceptions; namespace ProjectPlane.CollectionGenericObjects; @@ -26,7 +27,7 @@ public abstract class AbstractCompany public static int operator +(AbstractCompany company, DrawningShip ship) { - return company._collection.Insert(ship); + return company._collection.Insert(ship, 0); } public static DrawningShip? operator -(AbstractCompany company, int position) @@ -37,7 +38,14 @@ public abstract class AbstractCompany public DrawningShip? GetRandomObject() { Random rnd = new(); - return _collection?.Get(rnd.Next(GetMaxCount)); + try + { + return _collection?.Get(rnd.Next(GetMaxCount)); + } + catch (ObjectNotFoundException) + { + return null; + } } public Bitmap? Show() @@ -48,8 +56,15 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningShip? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningShip? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException) + { + continue; + } } return bitmap; } diff --git a/ProjectPlane/ProjectPlane/CollectionGenericObjects/ListGenericObjects.cs b/ProjectPlane/ProjectPlane/CollectionGenericObjects/ListGenericObjects.cs index 83b9eaa..bae9274 100644 --- a/ProjectPlane/ProjectPlane/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectPlane/ProjectPlane/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System.CodeDom.Compiler; +using ProjectPlane.Exceptions; +using System.CodeDom.Compiler; namespace ProjectPlane.CollectionGenericObjects; @@ -22,9 +23,10 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { + // TODO выброс ошибки, если выход за границы списка if (position < 0 || position >= Count) { - return null; + throw new PositionOutOfCollectionException(position); } return _collection[position]; @@ -32,9 +34,10 @@ public class ListGenericObjects : ICollectionGenericObjects public int Insert(T obj) { + // TODO выброс ошибки, если переполнение if (Count == _maxCount) { - return -1; + throw new CollectionOverflowException(Count); } _collection.Add(obj); @@ -43,9 +46,15 @@ public class ListGenericObjects : ICollectionGenericObjects public int Insert(T obj, int position) { - if (Count == _maxCount || position < 0 || position > Count) + // TODO выброс ошибки, если выход за границы списка + // TODO выброс ошибки, если переполнение + if (position < 0 || position > Count) { - return -1; + throw new PositionOutOfCollectionException(position); + } + if (Count == _maxCount) + { + throw new CollectionOverflowException(Count); } _collection.Insert(position, obj); @@ -54,20 +63,20 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Remove(int position) { + // TODO выброс ошибки, если выход за границы списка if (position < 0 || position > Count) { - return null; + throw new PositionOutOfCollectionException(position); } T? obj = _collection[position]; _collection.RemoveAt(position); - return obj; } public IEnumerable GetItems() { - for (int i = 0; i < Count; ++i) + for (int i = 0; i < Count; ++i) { yield return _collection[i]; } diff --git a/ProjectPlane/ProjectPlane/CollectionGenericObjects/Marina.cs b/ProjectPlane/ProjectPlane/CollectionGenericObjects/Marina.cs index 28b3ab4..af62f8d 100644 --- a/ProjectPlane/ProjectPlane/CollectionGenericObjects/Marina.cs +++ b/ProjectPlane/ProjectPlane/CollectionGenericObjects/Marina.cs @@ -1,4 +1,5 @@ using ProjectPlane.Drawnings; +using ProjectPlane.Exceptions; namespace ProjectPlane.CollectionGenericObjects; @@ -36,22 +37,30 @@ public class Marina : AbstractCompany for (int i = 0; i < (_collection?.Count ?? 0); i++) { - if (_collection?.Get(i) != null) + try { - int x = _placeSizeWidth * n; - int y = (10 + _placeSizeHeight * (_pictureHeight / _placeSizeHeight - 1)) - _placeSizeHeight * m; + if (_collection?.Get(i) != null) + { + int x = _placeSizeWidth * n; + int y = (10 + _placeSizeHeight * (_pictureHeight / _placeSizeHeight - 1)) - _placeSizeHeight * m; - _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); - _collection?.Get(i)?.SetPosition(x, y); + _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(i)?.SetPosition(x, y); + } + + if (n > 0) + n--; + else + { + n = _pictureWidth / _placeSizeWidth; + m++; + } } - - if (n > 0) - n--; - else + catch(ObjectNotFoundException) { - n = _pictureWidth / _placeSizeWidth; - m++; + break; } + } } } diff --git a/ProjectPlane/ProjectPlane/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectPlane/ProjectPlane/CollectionGenericObjects/MassiveGenericObjects.cs index f41acc3..f4d1b62 100644 --- a/ProjectPlane/ProjectPlane/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectPlane/ProjectPlane/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectPlane.CollectionGenericObjects; +using ProjectPlane.Exceptions; + +namespace ProjectPlane.CollectionGenericObjects; public class MassiveGenericObjects : ICollectionGenericObjects where T : class @@ -36,15 +38,23 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position < 0 || position > Count) + // TODO выброс ошибки, если выход за границы массива + // TODO выброс ошибки, если объект пустой + if (position < 0 || position >= Count) { - return null; + throw new PositionOutOfCollectionException(position); } + if (_collection[position] == null) + { + throw new ObjectNotFoundException(position); + } + return _collection[position]; } public int Insert(T obj) { + // TODO выброс ошибки, если переполнение for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -53,14 +63,17 @@ public class MassiveGenericObjects : ICollectionGenericObjects return i; } } - return -1; + + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - if (position < 0 || position > Count) + // TODO выброс ошибки, если выход за границы массива + // TODO выброс ошибки, если переполнение + if (position < 0 || position >= Count) { - return -1; + throw new PositionOutOfCollectionException(position); } if (_collection[position] == null) @@ -74,7 +87,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (_collection[i] == null) { _collection[i] = obj; - return position; + return i; } } @@ -83,18 +96,24 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (_collection[i] == null) { _collection[i] = obj; - return position; + return i; } } - return -1; + throw new CollectionOverflowException(Count); } public T? Remove(int position) { - if (position < 0 || position > Count || _collection[position] == null) + // TODO выброс ошибки, если выход за границы массива + // TODO выброс ошибки, если объект пустой + if (position < 0 || position >= Count) { - return null; + throw new PositionOutOfCollectionException(position); + } + if (_collection[position] == null) + { + throw new ObjectNotFoundException(position); } T? obj = _collection[position]; diff --git a/ProjectPlane/ProjectPlane/CollectionGenericObjects/StorageCollection.cs b/ProjectPlane/ProjectPlane/CollectionGenericObjects/StorageCollection.cs index 9a6d871..2efd86d 100644 --- a/ProjectPlane/ProjectPlane/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectPlane/ProjectPlane/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectPlane.Drawnings; +using ProjectPlane.Exceptions; using System.Text; namespace ProjectPlane.CollectionGenericObjects; @@ -62,115 +63,111 @@ public class StorageCollection _storages.Remove(name); } - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new NullReferenceException("В хранилище отсутствуют коллекции для сохранения"); } + if (File.Exists(filename)) { File.Delete(filename); } - StringBuilder sb = new(); - - sb.Append(_collectionKey); - foreach (KeyValuePair> value in - _storages) + using (StreamWriter sw = new StreamWriter(filename)) { - sb.Append(Environment.NewLine); - // не сохраняем пустые коллекции - if (value.Value.Count == 0) - { - continue; - } + sw.Write(_collectionKey); - sb.Append(value.Key); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.MaxCount); - sb.Append(_separatorForKeyValue); - - foreach (T? item in value.Value.GetItems()) + foreach (KeyValuePair> value in _storages) { - string data = item?.GetDataForSave() ?? string.Empty; - if (string.IsNullOrEmpty(data)) + sw.Write(Environment.NewLine); + // не сохраняем пустые коллекции + if (value.Value.Count == 0) { continue; } - sb.Append(data); - sb.Append(_separatorItems); + + sw.Write(value.Key); + sw.Write(_separatorForKeyValue); + sw.Write(value.Value.GetCollectionType); + sw.Write(_separatorForKeyValue); + sw.Write(value.Value.MaxCount); + sw.Write(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + + if (string.IsNullOrEmpty(data)) + { + continue; + } + sw.Write(data); + sw.Write(_separatorItems); + } } } - using FileStream fs = new(filename, FileMode.Create); - byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); - fs.Write(info, 0, info.Length); - return true; } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не существует"); } - string bufferTextFromFile = ""; - using (FileStream fs = new(filename, FileMode.Open)) - { - byte[] b = new byte[fs.Length]; - UTF8Encoding temp = new(true); - while (fs.Read(b, 0, b.Length) > 0) - { - bufferTextFromFile += temp.GetString(b); - } - } - string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, - StringSplitOptions.RemoveEmptyEntries); - if (strs == null || strs.Length == 0) - { - return false; - } - if (!strs[0].Equals(_collectionKey)) - { - //если нет такой записи, то это не те данные - return false; - } - _storages.Clear(); - foreach (string data in strs) + using (StreamReader sr = new(filename)) { - string[] record = data.Split(_separatorForKeyValue, - StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + string line = sr.ReadLine(); + + if (line == null || line.Length == 0) { - continue; + throw new FileFormatException("В файле нет данных"); } - CollectionType collectionType = - (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = - StorageCollection.CreateCollection(collectionType); - if (collection == null) + if (!line.Equals(_collectionKey)) { - return false; + throw new FileFormatException("В файле неверные данные"); } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, - StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) + _storages.Clear(); + + while ((line = sr.ReadLine()) != null) { - if (elem?.CreateDrawningShip() is T ship) + string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) { - if (collection.Insert(ship) == -1) + continue; + } + + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + if (collection == null) + { + throw new InvalidOperationException("Не удалось создать коллекцию"); + } + + collection.MaxCount = Convert.ToInt32(record[2]); + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + if (elem?.CreateDrawningShip() is T ship) { - return false; + try + { + if (collection.Insert(ship) == -1) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new OverflowException("Коллекция переполнена", ex); + } } } + _storages.Add(record[0], collection); } - _storages.Add(record[0], collection); } - return true; } public ICollectionGenericObjects? this[string name] diff --git a/ProjectPlane/ProjectPlane/Exceptions/CollectionOverflowException.cs b/ProjectPlane/ProjectPlane/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..7fedf63 --- /dev/null +++ b/ProjectPlane/ProjectPlane/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,15 @@ +using System.Runtime.Serialization; +namespace ProjectPlane.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/ProjectPlane/ProjectPlane/Exceptions/ObjectNotFoundException.cs b/ProjectPlane/ProjectPlane/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..8e13dc7 --- /dev/null +++ b/ProjectPlane/ProjectPlane/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,15 @@ +using System.Runtime.Serialization; +namespace ProjectPlane.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) { } +} + diff --git a/ProjectPlane/ProjectPlane/Exceptions/PositionOutOfCollectionException.cs b/ProjectPlane/ProjectPlane/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..5761afb --- /dev/null +++ b/ProjectPlane/ProjectPlane/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,15 @@ +using System.Runtime.Serialization; +namespace ProjectPlane.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) { } +} diff --git a/ProjectPlane/ProjectPlane/FormShipCollection.Designer.cs b/ProjectPlane/ProjectPlane/FormShipCollection.Designer.cs index b9c59ee..7834076 100644 --- a/ProjectPlane/ProjectPlane/FormShipCollection.Designer.cs +++ b/ProjectPlane/ProjectPlane/FormShipCollection.Designer.cs @@ -66,9 +66,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(ComboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(785, 24); + groupBoxTools.Location = new Point(853, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(200, 672); + groupBoxTools.Size = new Size(200, 692); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -248,7 +248,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(785, 672); + pictureBox.Size = new Size(853, 692); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -257,7 +257,7 @@ menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(985, 24); + menuStrip.Size = new Size(1053, 24); menuStrip.TabIndex = 2; menuStrip.Text = "menuStrip"; // @@ -288,7 +288,7 @@ // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(985, 696); + ClientSize = new Size(1053, 716); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); diff --git a/ProjectPlane/ProjectPlane/FormShipCollection.cs b/ProjectPlane/ProjectPlane/FormShipCollection.cs index 1c82939..0d92b02 100644 --- a/ProjectPlane/ProjectPlane/FormShipCollection.cs +++ b/ProjectPlane/ProjectPlane/FormShipCollection.cs @@ -1,5 +1,7 @@ using ProjectPlane.CollectionGenericObjects; using ProjectPlane.Drawnings; +using ProjectPlane.Exceptions; +using Microsoft.Extensions.Logging; namespace ProjectPlane; @@ -9,10 +11,13 @@ public partial class FormShipCollection : Form private AbstractCompany? _company = null; - public FormShipCollection() + private readonly ILogger _logger; + + public FormShipCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) @@ -29,19 +34,24 @@ public partial class FormShipCollection : Form private void SetShip(DrawningShip? ship) { - if (_company == null || ship == null) + try { - return; - } + if (_company == null || ship == null) + { + return; + } - if (_company + ship != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if (_company + ship != -1) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Добавлен объект {ship.GetDataForSave()}"); + pictureBox.Image = _company.Show(); + } } - else + catch (CollectionOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"Ошибка: {ex.Message}"); } } @@ -58,15 +68,25 @@ public partial class FormShipCollection : Form return; } - int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + try { - MessageBox.Show("Объект удалён"); - pictureBox.Image = _company.Show(); + int pos = Convert.ToInt32(maskedTextBoxPosition.Text); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation($"Удален объект по позиции {pos}"); + pictureBox.Image = _company.Show(); + } } - else + catch (ObjectNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogError($"Ошибка: {ex.Message}"); + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show(ex.Message); + _logger.LogError($"Ошибка: {ex.Message}"); } } @@ -192,15 +212,16 @@ public partial class FormShipCollection : 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); } } } @@ -209,16 +230,17 @@ public partial class FormShipCollection : 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/ProjectPlane/ProjectPlane/Program.cs b/ProjectPlane/ProjectPlane/Program.cs index 30a1b73..ad3c42d 100644 --- a/ProjectPlane/ProjectPlane/Program.cs +++ b/ProjectPlane/ProjectPlane/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; +using Serilog; + namespace ProjectPlane { internal static class Program @@ -8,10 +13,28 @@ namespace ProjectPlane [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 FormShipCollection()); + + ServiceCollection services = new(); + 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); + var config = new ConfigurationBuilder() + .AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true) + .Build(); + option.AddSerilog(Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(config) + .CreateLogger()); + }); } } } \ No newline at end of file diff --git a/ProjectPlane/ProjectPlane/ProjectPlane.csproj b/ProjectPlane/ProjectPlane/ProjectPlane.csproj index 244387d..d2143da 100644 --- a/ProjectPlane/ProjectPlane/ProjectPlane.csproj +++ b/ProjectPlane/ProjectPlane/ProjectPlane.csproj @@ -8,6 +8,19 @@ enable + + + + + + + + + + + + + True @@ -23,4 +36,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectPlane/ProjectPlane/ShipDelegate.cs b/ProjectPlane/ProjectPlane/ShipDelegate.cs deleted file mode 100644 index fe387d3..0000000 --- a/ProjectPlane/ProjectPlane/ShipDelegate.cs +++ /dev/null @@ -1,5 +0,0 @@ -using ProjectPlane.Drawnings; - -namespace ProjectPlane; - -public delegate void ShipDelegate(DrawningShip ship); diff --git a/ProjectPlane/ProjectPlane/log20240505.txt b/ProjectPlane/ProjectPlane/log20240505.txt new file mode 100644 index 0000000..e7ddd15 --- /dev/null +++ b/ProjectPlane/ProjectPlane/log20240505.txt @@ -0,0 +1,35 @@ +2024-05-05 19:31:54.5854 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:37:42.0203 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:37:45.8102 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:37:49.7304 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:37:53.9630 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityContainer:100:100:White:Black:False:False +2024-05-05 19:37:57.7237 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:38:01.6675 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:38:06.7083 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:38:11.3735 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:38:15.1331 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:38:20.0620 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:38:24.7261 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:38:31.0722 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:38:34.3915 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:38:40.7924 | WARNING | ProjectPlane.FormShipCollection | Ошибка: В коллекции превышено допустимое количество: 13 +2024-05-05 19:44:19.0599 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:44:23.5467 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:46:35.2923 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:46:39.0113 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:46:41.8356 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:46:45.7168 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:46:49.4368 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:46:52.7510 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:46:57.4698 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:47:00.6705 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:47:03.5259 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:47:06.1029 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:47:09.0793 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:47:11.9753 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:47:15.0238 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:47:18.0164 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:47:21.2964 | INFORMATION | ProjectPlane.FormShipCollection | Добавлен объект EntityShip:100:100:White +2024-05-05 19:47:26.9699 | WARNING | ProjectPlane.FormShipCollection | Ошибка: В коллекции превышено допустимое количество: 15 +2024-05-05 19:47:37.1140 | INFORMATION | ProjectPlane.FormShipCollection | Удален объект по позиции 5 +2024-05-05 19:47:41.2912 | ERROR | ProjectPlane.FormShipCollection | Ошибка: Не найден объект по позиции 5 diff --git a/ProjectPlane/ProjectPlane/serilogConfig.json b/ProjectPlane/ProjectPlane/serilogConfig.json new file mode 100644 index 0000000..1a2bc2d --- /dev/null +++ b/ProjectPlane/ProjectPlane/serilogConfig.json @@ -0,0 +1,25 @@ +{ + "AllowedHosts": "*", + "Serilog": { + "Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ], + "MinimumLevel": { + "Default": "Information", + "Override": { + "Microsoft": "Warning", + "System": "Warning" + } + }, + "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ], + "WriteTo": [ + { "Name": "Console" }, + { + "Name": "File", + "Args": { + "path": "C:\\Users\\rozko\\\\Documents\\Labs_OOP\\ProjectPlane\\ProjectPlane\\log.txt", + "rollingInterval": "Day", + "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff} | {Level:u} | {SourceContext} | {Message:1j}{NewLine}{Exception}" + } + } + ] + } +} \ No newline at end of file