diff --git a/Kursach/Kursach.sln b/Kursach/Kursach.sln new file mode 100644 index 0000000..4bec3a3 --- /dev/null +++ b/Kursach/Kursach.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.7.34024.191 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kursach", "Kursach\Kursach.csproj", "{F7A92B07-FEB7-46DF-95FA-0942077ADE41}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F7A92B07-FEB7-46DF-95FA-0942077ADE41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F7A92B07-FEB7-46DF-95FA-0942077ADE41}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F7A92B07-FEB7-46DF-95FA-0942077ADE41}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F7A92B07-FEB7-46DF-95FA-0942077ADE41}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {0F654BCD-A24D-4152-A016-59A66A97ADC9} + EndGlobalSection +EndGlobal diff --git a/Kursach/Kursach/Deque.cs b/Kursach/Kursach/Deque.cs new file mode 100644 index 0000000..c04cab8 --- /dev/null +++ b/Kursach/Kursach/Deque.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Kursach +{ + public class Deque + { + public LinkedList? list; + + public int numElems; + + public Deque() + { + list = new LinkedList(); + numElems = 0; + } + + public void InsertFirst(int value) + { + list.AddFirst(value); + } + + public void InsertLast(int value) + { + list.AddLast(value); + } + + public int PopFirst() + { + int temp = list.getHead(); + list.RemoveFirst(); + return temp; + } + + public int PopLast() + { + int temp = list.getTail(); + list.RemoveLast(); + return temp; + } + + public bool isEmpty() + { + return list.IsEmpty(); + } + + public void Clear() + { + list.Clear(); + } + } +} diff --git a/Kursach/Kursach/Form1.Designer.cs b/Kursach/Kursach/Form1.Designer.cs new file mode 100644 index 0000000..571e3ba --- /dev/null +++ b/Kursach/Kursach/Form1.Designer.cs @@ -0,0 +1,145 @@ +namespace Kursach +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + textBoxInput = new TextBox(); + buttonAddFirst = new Button(); + buttonAddLast = new Button(); + buttonDelFirst = new Button(); + buttonDelLast = new Button(); + buttonClear = new Button(); + button = new Button(); + groupBoxControls = new GroupBox(); + groupBoxControls.SuspendLayout(); + SuspendLayout(); + // + // textBoxInput + // + textBoxInput.Location = new Point(6, 30); + textBoxInput.Name = "textBoxInput"; + textBoxInput.Size = new Size(333, 31); + textBoxInput.TabIndex = 0; + // + // buttonAddFirst + // + buttonAddFirst.Location = new Point(6, 67); + buttonAddFirst.Name = "buttonAddFirst"; + buttonAddFirst.Size = new Size(104, 62); + buttonAddFirst.TabIndex = 1; + buttonAddFirst.Text = "Добавить в начало"; + buttonAddFirst.UseVisualStyleBackColor = true; + // + // buttonAddLast + // + buttonAddLast.Location = new Point(116, 67); + buttonAddLast.Name = "buttonAddLast"; + buttonAddLast.Size = new Size(104, 62); + buttonAddLast.TabIndex = 2; + buttonAddLast.Text = "Добавить в конец"; + buttonAddLast.UseVisualStyleBackColor = true; + // + // buttonDelFirst + // + buttonDelFirst.Location = new Point(253, 67); + buttonDelFirst.Name = "buttonDelFirst"; + buttonDelFirst.Size = new Size(104, 62); + buttonDelFirst.TabIndex = 3; + buttonDelFirst.Text = "Извлечь из начала"; + buttonDelFirst.UseVisualStyleBackColor = true; + // + // buttonDelLast + // + buttonDelLast.Location = new Point(363, 67); + buttonDelLast.Name = "buttonDelLast"; + buttonDelLast.Size = new Size(104, 62); + buttonDelLast.TabIndex = 4; + buttonDelLast.Text = "Извлечь из конца"; + buttonDelLast.UseVisualStyleBackColor = true; + // + // buttonClear + // + buttonClear.Location = new Point(497, 67); + buttonClear.Name = "buttonClear"; + buttonClear.Size = new Size(104, 62); + buttonClear.TabIndex = 5; + buttonClear.Text = "Очистить очередь"; + buttonClear.UseVisualStyleBackColor = true; + // + // button + // + button.BackColor = Color.FromArgb(192, 0, 0); + button.Location = new Point(607, 67); + button.Name = "button"; + button.Size = new Size(104, 62); + button.TabIndex = 6; + button.Text = "Очистить очередь"; + button.UseVisualStyleBackColor = false; + // + // groupBoxControls + // + groupBoxControls.Controls.Add(textBoxInput); + groupBoxControls.Controls.Add(button); + groupBoxControls.Controls.Add(buttonAddFirst); + groupBoxControls.Controls.Add(buttonClear); + groupBoxControls.Controls.Add(buttonAddLast); + groupBoxControls.Controls.Add(buttonDelLast); + groupBoxControls.Controls.Add(buttonDelFirst); + groupBoxControls.Dock = DockStyle.Top; + groupBoxControls.Location = new Point(0, 0); + groupBoxControls.Name = "groupBoxControls"; + groupBoxControls.Size = new Size(800, 146); + groupBoxControls.TabIndex = 7; + groupBoxControls.TabStop = false; + groupBoxControls.Text = "АТД дек"; + // + // Form1 + // + AutoScaleDimensions = new SizeF(10F, 25F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 568); + Controls.Add(groupBoxControls); + Name = "Form1"; + Text = "Form1"; + groupBoxControls.ResumeLayout(false); + groupBoxControls.PerformLayout(); + ResumeLayout(false); + } + + #endregion + + private TextBox textBoxInput; + private Button buttonAddFirst; + private Button buttonAddLast; + private Button buttonDelFirst; + private Button buttonDelLast; + private Button buttonClear; + private Button button; + private GroupBox groupBoxControls; + } +} \ No newline at end of file diff --git a/Kursach/Kursach/Form1.cs b/Kursach/Kursach/Form1.cs new file mode 100644 index 0000000..14b9fee --- /dev/null +++ b/Kursach/Kursach/Form1.cs @@ -0,0 +1,10 @@ +namespace Kursach +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + } +} \ No newline at end of file diff --git a/Kursach/Kursach/Form1.resx b/Kursach/Kursach/Form1.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/Kursach/Kursach/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Kursach/Kursach/Kursach.csproj b/Kursach/Kursach/Kursach.csproj new file mode 100644 index 0000000..c2414c4 --- /dev/null +++ b/Kursach/Kursach/Kursach.csproj @@ -0,0 +1,12 @@ + + + + WinExe + net7.0-windows + enable + true + enable + true + + + \ No newline at end of file diff --git a/Kursach/Kursach/LinkedList.cs b/Kursach/Kursach/LinkedList.cs new file mode 100644 index 0000000..56874ec --- /dev/null +++ b/Kursach/Kursach/LinkedList.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Kursach +{ + + public class LinkedList + { + private Node? head; + private Node? tail; + private int numElems; + public LinkedList() + { + head = null; + tail = null; + numElems = 0; + } + public void AddLast(T value) + { + Node node = new Node(value); + if (head == null) + { + head = node; + } + else + { + tail.next = node; + } + tail = node; + numElems++; + } + + public void AddFirst(T value) + { + Node node = new Node(value); + if (numElems == 0) + { + head = node; + tail = head; + } + else + { + node.next = head; + } + head = node; + numElems++; + + } + + public bool RemoveFirst() + { + if (head == null) + { + return false; + } + if (head == tail) + { + head = tail = null; + } + else + { + head = head.next; + } + numElems--; + return true; + } + public bool RemoveLast() + { + if (head == null) + { + return false; + } + if (head == tail) + { + head = tail = null; + } + else + { + Node? prev = null; + Node? curr = head; + while (curr.next != null) + { + prev = curr; + curr = curr.next; + } + + tail = prev; + tail.next = null; + } + + numElems--; + return true; + } + public bool Contains(T value) + { + Node? curr = head; + while (curr != null) + { + if (curr.data.Equals(value)) + { + return true; + } + curr = curr.next; + } + return false; + } + public void Clear() + { + head = null; + tail = null; + numElems = 0; + } + public bool IsEmpty() + { + return numElems==0; + } + public T getHead() + { + return head.data; + } + public T getTail() + { + return tail.data; + } + } + unsafe public class Node + { + public Node next { get; set; } + public T data { get; set; } + public Node(T data) + { + this.data = data; + } + } +} diff --git a/Kursach/Kursach/Program.cs b/Kursach/Kursach/Program.cs new file mode 100644 index 0000000..c15e408 --- /dev/null +++ b/Kursach/Kursach/Program.cs @@ -0,0 +1,17 @@ +namespace Kursach +{ + internal static class Program + { + /// + /// The main entry point for the application. + /// + [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 Form1()); + } + } +} \ No newline at end of file diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs index 708bdf0..4425eca 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectLinkor.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -41,47 +42,32 @@ public class ListGenericObjects : ICollectionGenericObjects { _collection = new(); } - public T? Get(int position) + public T Get(int position) { - // TODO проверка позиции - if (position <= Count) - { - return _collection[position]; - } - else - return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(); + return _collection[position]; } public int Insert(T obj) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO вставка в конец набора - if (Count + 1 > _maxCount) - return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; } public int Insert(T obj, int position) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO проверка позиции - // TODO вставка по позиции - if (Count + 1 > _maxCount) - return -1; - if (position < 0 || position > Count) - return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); - return 1; - + return position; + } - public T? Remove(int position) + public T Remove(int position) { - // TODO проверка позиции - // TODO удаление объекта из списка - if (position < 0 || position > Count) - return null; - T? temp = _collection[position]; + if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; _collection.RemoveAt(position); - return temp; + return obj; } public IEnumerable GetItems() diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs index 01a5f43..38fe734 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectLinkor.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -48,12 +49,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } public T? Get(int position) { - if (position <= Count) - { - return _collection[position]; - } - else - return null; + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(); + return _collection[position]; } public int Insert(T obj) { @@ -65,47 +62,47 @@ public class MassiveGenericObjects : ICollectionGenericObjects return i; } } - return -1; - + throw new CollectionOverflowException(); } public int Insert(T obj, int position) { - // TODO проверка позиции - // TODO проверка, что элемент массива по этой позиции пустой, если нет, то - // ищется свободное место после этой позиции и идет вставка туда - // если нет после, ищем до - // TODO вставка - if (position < Count) + if (position < 0 || position >= Count) { - if (position < 0 || position >= Count) + throw new PositionOutOfCollectionException(); + } + if (_collection[position] == null) + { + _collection[position] = obj; + return position; + + } + int temp = position + 1; + while (temp < Count) + { + if (_collection[temp] == null) { - return -1; + _collection[temp] = obj; + return temp; } - if (_collection[position] == null) + ++temp; + } + temp = position - 1; + while (temp >= 0) + { + if (_collection[temp] == null) { - _collection[position] = obj; - return position; - } - else - { - for (int i = 0; i < Count; i++) - { - if (_collection[i] == null) - { - _collection[i] = obj; - return i; - } - } + _collection[temp] = obj; + return temp; } + --temp; } return -1; } - public T? Remove(int position) + public T Remove(int position) { - // TODO проверка позиции - // TODO удаление объекта из массива, присвоив элементу массива значение null - if (position >= Count || position < 0) return null; - T? myObject = _collection[position]; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); + if (_collection[position] == null) throw new ObjectNotFoundException(); + T myObject = _collection[position]; _collection[position] = null; return myObject; } diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs index c9b152e..87aa1d7 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectLinkor.Drawnings; +using ProjectLinkor.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -91,11 +92,11 @@ public class StorageCollection return _storages[name]; } } - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) { @@ -131,30 +132,27 @@ public class StorageCollection } } } - return true; } /// /// Загрузка информации по кораблям в хранилище из файла /// /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не существует"); } using (StreamReader reader = new(filename)) { string line = reader.ReadLine(); if (line == null || line.Length == 0) { - return false; + throw new ArgumentException("В файле нет данных"); } if (!line.Equals(_collectionKey)) { - //если нет такой записи, то это не те данные - return false; + throw new InvalidDataException("В файле неверные данные"); } _storages.Clear(); while ((line = reader.ReadLine()) != null) @@ -166,11 +164,9 @@ public class StorageCollection continue; } CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - return false; - } + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ?? + throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]); ; + collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); @@ -178,16 +174,22 @@ public class StorageCollection { if (elem?.CreateDrawingShip() is T ship) { - if (collection.Insert(ship) == -1) + try { - return false; + if (collection.Insert(ship) == -1) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new CollectionOverflowException("Коллекция переполнена", ex); } } } _storages.Add(record[0], collection); } } - return true; } /// /// Создание коллекции по типу diff --git a/ProjectAirbus/ProjectAirbus/Exceptions/CollectionOverflowException.cs b/ProjectAirbus/ProjectAirbus/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..7401ac4 --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectLinkor.Exceptions; +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +public 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/ProjectAirbus/ProjectAirbus/Exceptions/ObjectNotFoundException.cs b/ProjectAirbus/ProjectAirbus/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..4124eee --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectLinkor.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/ProjectAirbus/ProjectAirbus/Exceptions/PositionOutOfCollectionException.cs b/ProjectAirbus/ProjectAirbus/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..e7fec37 --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectLinkor.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/ProjectAirbus/ProjectAirbus/FormShipCollection.cs b/ProjectAirbus/ProjectAirbus/FormShipCollection.cs index 53998ff..6094f85 100644 --- a/ProjectAirbus/ProjectAirbus/FormShipCollection.cs +++ b/ProjectAirbus/ProjectAirbus/FormShipCollection.cs @@ -1,5 +1,7 @@ -using ProjectLinkor.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectLinkor.CollectionGenericObjects; using ProjectLinkor.Drawnings; +using ProjectLinkor.Exceptions; using System; using System.Collections.Generic; using System.ComponentModel; @@ -9,6 +11,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using System.Xml.Linq; namespace ProjectLinkor; /// @@ -22,13 +25,16 @@ public partial class FormShipCollection : Form /// Компания /// private AbstractCompany? _company = null; + + private readonly ILogger _logger; /// /// Конструктор /// - public FormShipCollection() + public FormShipCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } /// /// Выбор компании @@ -56,14 +62,17 @@ public partial class FormShipCollection : Form { return; } - if (_company + ship != -1) + try { + int addingObject = (_company + ship); MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Добавлен объект {ship.GetDataForSave()}"); pictureBox.Image = _company.Show(); } - else + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); } } @@ -71,6 +80,7 @@ public partial class FormShipCollection : Form { if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) { + _logger.LogWarning("Удаление объекта из несуществующей коллекции"); return; } if (MessageBox.Show("Удалить объект?", "Удаление", @@ -79,16 +89,23 @@ public partial class FormShipCollection : Form return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + try { + object decrementObject = _company - pos; MessageBox.Show("Объект удален"); + _logger.LogInformation($"Удален по позиции {pos}"); pictureBox.Image = _company.Show(); } - else + catch (ObjectNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show("Объект не найден "); + _logger.LogWarning($"Удаление не найденного объекта в позиции {pos} "); + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show("Удаление вне рамках коллекции"); + _logger.LogWarning($"Удаление объекта за пределами коллекции {pos} "); } - } /// /// Передача объекта в другую форму @@ -106,11 +123,17 @@ public partial class FormShipCollection : Form int counter = 100; while (ship == null) { - ship = _company.GetRandomObject(); - counter--; - if (counter <= 0) + try { - break; + ship = _company.GetRandomObject(); + } + catch (ObjectNotFoundException) + { + counter--; + if (counter <= 0) + { + break; + } } } if (ship == null) @@ -150,6 +173,7 @@ public partial class FormShipCollection : Form { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не заполненная коллекция"); return; } CollectionType collectionType = CollectionType.None; @@ -162,6 +186,7 @@ public partial class FormShipCollection : Form collectionType = CollectionType.List; } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}"); RerfreshListBoxItems(); } /// @@ -178,13 +203,16 @@ public partial class FormShipCollection : Form if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); + _logger.LogWarning("Удаление невыбранной коллекции"); return; } + string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation($"Удалена коллекция: {name}"); RerfreshListBoxItems(); } /// @@ -213,6 +241,7 @@ public partial class FormShipCollection : Form if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); + _logger.LogWarning("Создание компании невыбранной коллекции"); return; } ICollectionGenericObjects? collection = @@ -220,6 +249,7 @@ public partial class FormShipCollection : Form if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); + _logger.LogWarning("Не удалось инициализировать коллекцию"); return; } switch (comboBoxSelectorCompany.Text) @@ -242,15 +272,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); } } } @@ -263,14 +294,17 @@ public partial class FormShipCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName); RerfreshListBoxItems(); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось сохранить", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/ProjectAirbus/ProjectAirbus/Program.cs b/ProjectAirbus/ProjectAirbus/Program.cs index eef40ba..30c672b 100644 --- a/ProjectAirbus/ProjectAirbus/Program.cs +++ b/ProjectAirbus/ProjectAirbus/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; +using Serilog; + namespace ProjectLinkor { internal static class Program @@ -11,7 +16,30 @@ namespace ProjectLinkor // 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 => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "serilogConfig.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/ProjectAirbus/ProjectAirbus/ProjectLinkor.csproj b/ProjectAirbus/ProjectAirbus/ProjectLinkor.csproj index 244387d..a5861f7 100644 --- a/ProjectAirbus/ProjectAirbus/ProjectLinkor.csproj +++ b/ProjectAirbus/ProjectAirbus/ProjectLinkor.csproj @@ -8,6 +8,18 @@ enable + + + + + + + + + + + + True @@ -23,4 +35,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectAirbus/ProjectAirbus/serilogConfig.json b/ProjectAirbus/ProjectAirbus/serilogConfig.json new file mode 100644 index 0000000..e9e9b9e --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/serilogConfig.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": "Linkor" + } + } +} \ No newline at end of file