From 3cae6dc2f4344e8fb3fa467e7d7e879a063fc6c4 Mon Sep 17 00:00:00 2001 From: sqdselo <147947144+sqdselo@users.noreply.github.com> Date: Sun, 28 Apr 2024 23:17:48 +0400 Subject: [PATCH 1/9] =?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=20(=D0=B2=D1=81=D0=B5=20=D0=BA=D1=80=D0=BE=D0=BC?= =?UTF-8?q?=D0=B5=20=D0=BB=D0=BE=D0=B3=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../CollectionGenericObjects/Garage.cs | 4 +- .../ListGenericObjects.cs | 68 +++++++++----- .../MassivGenericObjects.cs | 88 +++++++++++++------ .../StorageCollection.cs | 31 ++++--- .../Exceptions/CollectionOverflowException.cs | 19 ++++ .../Exceptions/ObjectNotFoundException.cs | 19 ++++ .../PositionOutOfCollectionException.cs | 19 ++++ .../HoistingCrane/FormCarCollection.cs | 49 ++++++++--- 9 files changed, 222 insertions(+), 77 deletions(-) create mode 100644 HoistingCrane/HoistingCrane/Exceptions/CollectionOverflowException.cs create mode 100644 HoistingCrane/HoistingCrane/Exceptions/ObjectNotFoundException.cs create mode 100644 HoistingCrane/HoistingCrane/Exceptions/PositionOutOfCollectionException.cs diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs index 98a10dc..1c50f33 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs @@ -31,7 +31,7 @@ namespace HoistingCrane.CollectionGenericObjects { get { - return (pictureWidth * pictureHeight) / (_placeSizeHeight * _placeSizeWidth)-3; + return (pictureWidth * pictureHeight) / (_placeSizeHeight * _placeSizeWidth)-2; } } public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects array) diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs index e2da629..0cf29d7 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs @@ -38,8 +38,9 @@ namespace HoistingCrane.CollectionGenericObjects { arr?.Get(i)?.SetPictureSize(pictureWidth, pictureHeight); arr?.Get(i)?.SetPosition(_placeSizeWidth * currentPosWidth + 25, _placeSizeHeight * currentPosHeight + 15); + } - + if (currentPosWidth > 0) currentPosWidth--; else @@ -51,7 +52,6 @@ namespace HoistingCrane.CollectionGenericObjects { break; } - } } } diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs index c92ca52..73f740c 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using HoistingCrane.Exceptions; +using System; using System.CodeDom.Compiler; namespace HoistingCrane.CollectionGenericObjects @@ -44,47 +45,72 @@ namespace HoistingCrane.CollectionGenericObjects public T? Get(int position) { - // TODO проверка позиции - if (position >= Count || position < 0) return null; - return list[position]; + try + { + if (position >= Count || position < 0) + { + throw new PositionOutOfCollectionException(position); + } + return list[position]; + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show(ex.Message); + return null; + } } - - + public int Insert(T obj) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO вставка в конец набора - if (Count == _maxCount) + try { + if (Count == _maxCount) throw new CollectionOverflowException(Count); + list.Add(obj); + return Count; + } + catch(CollectionOverflowException ex) + { + MessageBox.Show(ex.Message); return -1; } - list.Add(obj); - return Count; } public int Insert(T obj, int position) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO проверка позиции - // TODO вставка по позиции - if (position < 0 || position >= Count || Count == _maxCount) + try { + if (position < 0 || position >= _maxCount) throw new PositionOutOfCollectionException(position); + if (Count == _maxCount) throw new CollectionOverflowException(Count); + list.Insert(position, obj); + return position; + } + catch (CollectionOverflowException ex) + { + MessageBox.Show(ex.Message); return -1; } - list.Insert(position, obj); - return position; + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show(ex.Message); + return -1; + } + } + public T? Remove(int position) { - // TODO проверка позиции - // TODO удаление объекта из списка - if (position >= 0 && position < list.Count) + try { + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); T? temp = list[position]; list.RemoveAt(position); return temp; } - return null; + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show(ex.Message); + return null; + } } public IEnumerable GetItems() diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs index afe3a36..7680ae0 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using HoistingCrane.Exceptions; +using System; namespace HoistingCrane.CollectionGenericObjects { @@ -39,11 +40,22 @@ namespace HoistingCrane.CollectionGenericObjects public T? Get(int position) { - if (position >= 0 && position < arr.Length) + try { + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + //if (arr[position] == null) throw new ObjectNotFoundException(position); return arr[position]; } - return null; + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show(ex.Message); + return null; + } + //catch (ObjectNotFoundException ex) + //{ + // MessageBox.Show(ex.Message); + // return null; + //} } public IEnumerable GetItems() @@ -56,45 +68,69 @@ namespace HoistingCrane.CollectionGenericObjects public int Insert(T obj) { - return Insert(obj, 0); + try + { + if (arr.Count(x => x != null) == MaxCount) throw new CollectionOverflowException(Count); + return Insert(obj, 0); + } + catch(CollectionOverflowException ex) + { + MessageBox.Show(ex.Message); + return -1; + } } public int Insert(T obj, int position) { - //todo Проверка позиции - if (position < 0 || position > Count) + try { + if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position); + + if (arr[position] == null) + { + arr[position] = obj; + return position; + } + else + { + if (Insert(obj, position + 1) != -1) + { + return position; + } + if (Insert(obj, position - 1) != -1) + { + return position; + } + return -1; + } + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show(ex.Message); return -1; } - - if (arr[position] == null) - { - arr[position] = obj; - return position; - } - else - { - if (Insert(obj, position + 1) != -1) - { - return position; - } - if (Insert(obj, position - 1) != -1) - { - return position; - } - } - return -1; } public T? Remove(int position) { - if (position >= 0 && position < Count) + try { + if (position < 0 || position >= MaxCount) throw new PositionOutOfCollectionException(position); + if (arr[position] == null) throw new ObjectNotFoundException(position); T? temp = arr[position]; arr[position] = null; return temp; } - return null; + catch (ObjectNotFoundException ex) + { + MessageBox.Show(ex.Message); + return null; + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show(ex.Message); + return null; + } } } } diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs index d696adb..cb6a3f0 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using HoistingCrane.Drawning; +using HoistingCrane.Exceptions; using System; using System.Text; @@ -79,11 +80,11 @@ namespace HoistingCrane.CollectionGenericObjects /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (dict.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -125,8 +126,6 @@ namespace HoistingCrane.CollectionGenericObjects } } - return true; - } /// @@ -134,22 +133,22 @@ namespace HoistingCrane.CollectionGenericObjects // /// // /// Путь и имя файла // /// 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("В файле неверные данные"); } dict.Clear(); string strs = ""; @@ -164,23 +163,29 @@ namespace HoistingCrane.CollectionGenericObjects 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?.CreateDrawningTrackedVehicle() is T truck) + if (elem?.CreateDrawningTrackedVehicle() is T crane) { - if (collection.Insert(truck) == -1) + try { - return false; + if (collection.Insert(crane) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch(CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена"); } } } dict.Add(record[0], collection); } - return true; } } /// diff --git a/HoistingCrane/HoistingCrane/Exceptions/CollectionOverflowException.cs b/HoistingCrane/HoistingCrane/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..da3c19f --- /dev/null +++ b/HoistingCrane/HoistingCrane/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace HoistingCrane.Exceptions +{ + [Serializable] + public class CollectionOverflowException : ApplicationException + { + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: count" + count) { } + public CollectionOverflowException() : base(){ } + public CollectionOverflowException(string message) : base(message) { } + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/HoistingCrane/HoistingCrane/Exceptions/ObjectNotFoundException.cs b/HoistingCrane/HoistingCrane/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..c833095 --- /dev/null +++ b/HoistingCrane/HoistingCrane/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace HoistingCrane.Exceptions +{ + [Serializable] + public 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 context) : base(info, context) { } + } +} diff --git a/HoistingCrane/HoistingCrane/Exceptions/PositionOutOfCollectionException.cs b/HoistingCrane/HoistingCrane/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..e35263d --- /dev/null +++ b/HoistingCrane/HoistingCrane/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace HoistingCrane.Exceptions +{ + [Serializable] + public 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 context) : base(info, context){ } + } +} diff --git a/HoistingCrane/HoistingCrane/FormCarCollection.cs b/HoistingCrane/HoistingCrane/FormCarCollection.cs index 978fbe7..7fb63e8 100644 --- a/HoistingCrane/HoistingCrane/FormCarCollection.cs +++ b/HoistingCrane/HoistingCrane/FormCarCollection.cs @@ -49,10 +49,10 @@ namespace HoistingCrane MessageBox.Show("Объект добавлен"); pictureBox.Image = _company.Show(); } - else - { - MessageBox.Show("Не удалось добавить объект"); - } + //else + //{ + // MessageBox.Show("Не удалось добавить объект"); + //} } private static Color GetColor(Random random) { @@ -82,10 +82,10 @@ namespace HoistingCrane MessageBox.Show("Объект добавлен"); pictureBox.Image = _company.Show(); } - else - { - MessageBox.Show("Не удалось добавить объект"); - } + //else + //{ + // MessageBox.Show("Не удалось добавить объект"); + //} } private void buttonDeleteCar_Click(object sender, EventArgs e) @@ -105,10 +105,10 @@ namespace HoistingCrane MessageBox.Show("Объект удален!"); pictureBox.Image = _company.Show(); } - else - { - MessageBox.Show("Не удалось удалить объект"); - } + //else + //{ + // MessageBox.Show("Не удалось удалить объект"); + //} } private void buttonRefresh_Click(object sender, EventArgs e) { @@ -214,7 +214,17 @@ namespace HoistingCrane { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + bool saveSuccessful = false; + try + { + _storageCollection.SaveData(saveFileDialog.FileName); + saveSuccessful = true; + } + catch (Exception ex) + { + MessageBox.Show("Ошибка при сохранении данных: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + if (saveSuccessful) { MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } @@ -234,7 +244,18 @@ namespace HoistingCrane { if(openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + bool loadSuccessful = false; + try + { + _storageCollection.LoadData(openFileDialog.FileName); + loadSuccessful = true; + } + + catch(Exception ex) + { + MessageBox.Show("Ошибка при загрузке данных: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + if(loadSuccessful) { MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); RerfreshListBoxItems(); From 4fc0549d2efe03c4dd886ea8d169fea677c9efd4 Mon Sep 17 00:00:00 2001 From: sqdselo <147947144+sqdselo@users.noreply.github.com> Date: Mon, 29 Apr 2024 00:51:57 +0400 Subject: [PATCH 2/9] =?UTF-8?q?=D0=B4=D0=BE=D0=B4=D0=B5=D0=BB=D0=B0=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../HoistingCrane/FormCarCollection.cs | 112 +++++++++--------- HoistingCrane/HoistingCrane/FormCarConfig.cs | 1 + .../HoistingCrane/HoistingCrane.csproj | 11 ++ HoistingCrane/HoistingCrane/Program.cs | 23 +++- HoistingCrane/HoistingCrane/nlog.config | 13 ++ 5 files changed, 100 insertions(+), 60 deletions(-) create mode 100644 HoistingCrane/HoistingCrane/nlog.config diff --git a/HoistingCrane/HoistingCrane/FormCarCollection.cs b/HoistingCrane/HoistingCrane/FormCarCollection.cs index 7fb63e8..acd8ebf 100644 --- a/HoistingCrane/HoistingCrane/FormCarCollection.cs +++ b/HoistingCrane/HoistingCrane/FormCarCollection.cs @@ -1,5 +1,7 @@ using HoistingCrane.CollectionGenericObjects; using HoistingCrane.Drawning; +using HoistingCrane.Entities; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel; @@ -17,11 +19,16 @@ namespace HoistingCrane private AbstractCompany? _company; private readonly StorageCollection _storageCollection; - public FormCarCollection() + /// + /// Логгер + /// + private readonly ILogger logger; + public FormCarCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); panelCompanyTool.Enabled = false; + this.logger = logger; } private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) { @@ -49,10 +56,6 @@ namespace HoistingCrane MessageBox.Show("Объект добавлен"); pictureBox.Image = _company.Show(); } - //else - //{ - // MessageBox.Show("Не удалось добавить объект"); - //} } private static Color GetColor(Random random) { @@ -72,43 +75,47 @@ namespace HoistingCrane } private void SetCar(DrawningTrackedVehicle drawningTrackedVehicle) { - if (_company == null || drawningTrackedVehicle == null) + + try { + if (_company + drawningTrackedVehicle != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + logger.LogInformation("Добавлен объект DrawningTrackedVehicle"); + } + else + { + throw new Exception(); + } + } + catch (Exception ex) + { + logger.LogError("Не удалось добавить объект"); return; } - - if (_company + drawningTrackedVehicle != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - //else - //{ - // MessageBox.Show("Не удалось добавить объект"); - //} + } private void buttonDeleteCar_Click(object sender, EventArgs e) { - - if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) + try { + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) throw new Exception(); + if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) throw new Exception(); + int pos = Convert.ToInt32(maskedTextBox.Text); + if ((_company - pos) != null) + { + MessageBox.Show("Объект удален!"); + pictureBox.Image = _company.Show(); + logger.LogInformation("удален объект по позиции: {pos}", pos); + } + } + catch(Exception ex) + { + logger.LogError("Не удалось удалить объект по позиции: {pos}", Convert.ToInt32(maskedTextBox.Text)); return; } - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) - { - return; - } - int pos = Convert.ToInt32(maskedTextBox.Text); - if ((_company - pos) != null) - { - MessageBox.Show("Объект удален!"); - pictureBox.Image = _company.Show(); - } - //else - //{ - // MessageBox.Show("Не удалось удалить объект"); - //} } private void buttonRefresh_Click(object sender, EventArgs e) { @@ -148,6 +155,7 @@ namespace HoistingCrane listBoxCollection.Items.Add(colName); } } + logger.LogInformation("Коллекция успешно обновлена"); } private void buttonCollectionAdd_Click(object sender, EventArgs e) { @@ -184,17 +192,18 @@ namespace HoistingCrane } private void buttonCreateCompany_Click(object sender, EventArgs e) { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) + + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); return; } ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; - if (collection == null) + if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); return; - } + }; switch (comboBoxSelectorCompany.Text) { case "Хранилище": @@ -203,6 +212,8 @@ namespace HoistingCrane } panelCompanyTool.Enabled = true; RerfreshListBoxItems(); + + } /// @@ -214,23 +225,16 @@ namespace HoistingCrane { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - bool saveSuccessful = false; try { _storageCollection.SaveData(saveFileDialog.FileName); - saveSuccessful = true; + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } catch (Exception ex) { - MessageBox.Show("Ошибка при сохранении данных: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - if (saveSuccessful) - { - MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - else - { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -244,25 +248,17 @@ namespace HoistingCrane { if(openFileDialog.ShowDialog() == DialogResult.OK) { - bool loadSuccessful = false; try { _storageCollection.LoadData(openFileDialog.FileName); - loadSuccessful = true; - } - - catch(Exception ex) - { - MessageBox.Show("Ошибка при загрузке данных: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - if(loadSuccessful) - { MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); RerfreshListBoxItems(); + 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); } } } diff --git a/HoistingCrane/HoistingCrane/FormCarConfig.cs b/HoistingCrane/HoistingCrane/FormCarConfig.cs index 1908fc4..96a2990 100644 --- a/HoistingCrane/HoistingCrane/FormCarConfig.cs +++ b/HoistingCrane/HoistingCrane/FormCarConfig.cs @@ -31,6 +31,7 @@ namespace HoistingCrane panelColorPurple.MouseDown += panel_MouseDown; buttonCancel.Click += (sender, e) => Close(); } + /// /// Привязка метода к событию /// diff --git a/HoistingCrane/HoistingCrane/HoistingCrane.csproj b/HoistingCrane/HoistingCrane/HoistingCrane.csproj index 69ac652..5f40a60 100644 --- a/HoistingCrane/HoistingCrane/HoistingCrane.csproj +++ b/HoistingCrane/HoistingCrane/HoistingCrane.csproj @@ -12,6 +12,11 @@ + + + + + True @@ -27,4 +32,10 @@ + + + Always + + + \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/Program.cs b/HoistingCrane/HoistingCrane/Program.cs index 79d96ff..c5abf19 100644 --- a/HoistingCrane/HoistingCrane/Program.cs +++ b/HoistingCrane/HoistingCrane/Program.cs @@ -1,3 +1,7 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + namespace HoistingCrane { internal static class Program @@ -11,8 +15,23 @@ namespace HoistingCrane // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormCarCollection()); - + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + + } + /// + /// DI + /// + /// + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton().AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); } } } \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/nlog.config b/HoistingCrane/HoistingCrane/nlog.config new file mode 100644 index 0000000..3a13aee --- /dev/null +++ b/HoistingCrane/HoistingCrane/nlog.config @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file From d7cbb7356716c512c78730fd3e2e6e1ce6ed7915 Mon Sep 17 00:00:00 2001 From: sqdselo <147947144+sqdselo@users.noreply.github.com> Date: Mon, 29 Apr 2024 01:40:45 +0400 Subject: [PATCH 3/9] =?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 --- .../HoistingCrane/FormCarCollection.cs | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/HoistingCrane/HoistingCrane/FormCarCollection.cs b/HoistingCrane/HoistingCrane/FormCarCollection.cs index acd8ebf..cc3db0d 100644 --- a/HoistingCrane/HoistingCrane/FormCarCollection.cs +++ b/HoistingCrane/HoistingCrane/FormCarCollection.cs @@ -75,23 +75,23 @@ namespace HoistingCrane } private void SetCar(DrawningTrackedVehicle drawningTrackedVehicle) { - + if (_company == null || drawningTrackedVehicle == null) return; try { if (_company + drawningTrackedVehicle != -1) { MessageBox.Show("Объект добавлен"); pictureBox.Image = _company.Show(); - logger.LogInformation("Добавлен объект DrawningTrackedVehicle"); + logger.LogInformation("Добавлен объект {nameObject}", drawningTrackedVehicle.GetType().Name); } else { - throw new Exception(); + throw new Exception("Не удалось добавить объект. Заполнено максимальное количество ячеек"); } } catch (Exception ex) { - logger.LogError("Не удалось добавить объект"); + logger.LogInformation(ex.Message); return; } @@ -99,21 +99,22 @@ namespace HoistingCrane private void buttonDeleteCar_Click(object sender, EventArgs e) { + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return; + if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) return; try { - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) throw new Exception(); - if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) throw new Exception(); int pos = Convert.ToInt32(maskedTextBox.Text); if ((_company - pos) != null) { MessageBox.Show("Объект удален!"); pictureBox.Image = _company.Show(); - logger.LogInformation("удален объект по позиции: {pos}", pos); + logger.LogInformation("Удален объект по позиции: {pos} ", pos); } + else throw new Exception(); } catch(Exception ex) { - logger.LogError("Не удалось удалить объект по позиции: {pos}", Convert.ToInt32(maskedTextBox.Text)); + logger.LogInformation("Не удалось удалить объект по позиции: {pos}", Convert.ToInt32(maskedTextBox.Text)); return; } } @@ -169,14 +170,14 @@ namespace HoistingCrane if (radioButtonMassive.Checked) { collectionType = CollectionType.Massive; + logger.LogInformation("Создана коллекция типа: {name}", collectionType); } else if (radioButtonList.Checked) { collectionType = CollectionType.List; + logger.LogInformation("Создана коллекция типа: {name}", collectionType); } - _storageCollection.AddCollection(textBoxCollectionName.Text, - collectionType); - RerfreshListBoxItems(); + _storageCollection.AddCollection(textBoxCollectionName.Text,collectionType);RerfreshListBoxItems(); } private void buttonDeleteCollection_Click(object sender, EventArgs e) { @@ -189,6 +190,7 @@ namespace HoistingCrane return; _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); RerfreshListBoxItems(); + logger.LogInformation("Коллекция успешно удалена"); } private void buttonCreateCompany_Click(object sender, EventArgs e) { @@ -212,7 +214,7 @@ namespace HoistingCrane } panelCompanyTool.Enabled = true; RerfreshListBoxItems(); - + logger.LogInformation("Создана компания"); } From 5ae896d09f1986968baeeb9ed94570f1d0b2ab27 Mon Sep 17 00:00:00 2001 From: sqdselo Date: Mon, 29 Apr 2024 11:30:11 +0400 Subject: [PATCH 4/9] =?UTF-8?q?=D0=B2=20=D0=BF=D1=80=D0=BE=D1=86=D0=B5?= =?UTF-8?q?=D1=81=D1=81=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- HoistingCrane/HoistingCrane/nlog.config | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/HoistingCrane/HoistingCrane/nlog.config b/HoistingCrane/HoistingCrane/nlog.config index 3a13aee..0c93951 100644 --- a/HoistingCrane/HoistingCrane/nlog.config +++ b/HoistingCrane/HoistingCrane/nlog.config @@ -4,7 +4,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogLevel="Info"> - + From 2015e638fe64a0b258138a2e788b9f21828ce410 Mon Sep 17 00:00:00 2001 From: sqdselo <147947144+sqdselo@users.noreply.github.com> Date: Sat, 4 May 2024 15:57:24 +0400 Subject: [PATCH 5/9] 1 --- .../HoistingCrane/FormCarCollection.cs | 40 +++++++++---------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/HoistingCrane/HoistingCrane/FormCarCollection.cs b/HoistingCrane/HoistingCrane/FormCarCollection.cs index cc3db0d..8fb3fa7 100644 --- a/HoistingCrane/HoistingCrane/FormCarCollection.cs +++ b/HoistingCrane/HoistingCrane/FormCarCollection.cs @@ -99,24 +99,24 @@ namespace HoistingCrane private void buttonDeleteCar_Click(object sender, EventArgs e) { - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return; - if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) return; - try - { - int pos = Convert.ToInt32(maskedTextBox.Text); - if ((_company - pos) != null) - { - MessageBox.Show("Объект удален!"); - pictureBox.Image = _company.Show(); - logger.LogInformation("Удален объект по позиции: {pos} ", pos); - } - else throw new Exception(); - } - catch(Exception ex) - { - logger.LogInformation("Не удалось удалить объект по позиции: {pos}", Convert.ToInt32(maskedTextBox.Text)); - return; - } + //if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return; + //if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) return; + //try + //{ + // int pos = Convert.ToInt32(maskedTextBox.Text); + // if ((_company - pos) != null) + // { + // MessageBox.Show("Объект удален!"); + // pictureBox.Image = _company.Show(); + // logger.LogInformation("Удален объект по позиции: {pos} ", pos); + // } + // else throw new Exception(); + //} + //catch(Exception ex) + //{ + // logger.LogInformation("Не удалось удалить объект по позиции: {pos}", Convert.ToInt32(maskedTextBox.Text)); + // return; + //} } private void buttonRefresh_Click(object sender, EventArgs e) { @@ -233,7 +233,7 @@ namespace HoistingCrane MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - catch (Exception ex) + catch (FileNotFoundException ex) { MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); logger.LogError("Ошибка: {Message}", ex.Message); @@ -257,7 +257,7 @@ namespace HoistingCrane RerfreshListBoxItems(); logger.LogInformation("Загрузка в файл: {filename}", saveFileDialog.FileName); } - catch(Exception ex) + catch(FileNotFoundException ex) { MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); logger.LogError("Ошибка: {Message}", ex.Message); From 170e4abff07453aa496eb11adeef619cb873b0bf Mon Sep 17 00:00:00 2001 From: sqdselo <147947144+sqdselo@users.noreply.github.com> Date: Mon, 6 May 2024 17:35:33 +0400 Subject: [PATCH 6/9] =?UTF-8?q?=D0=A3=D0=B1=D1=80=D0=B0=D0=BB=20=D0=BB?= =?UTF-8?q?=D0=B8=D1=88=D0=BD=D0=B8=D0=B5=20=D1=8E=D0=B7=D0=B8=D0=BD=D0=B3?= =?UTF-8?q?=D0=B8,=20=D1=81=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB=20=D0=B8=D1=81?= =?UTF-8?q?=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BD=D0=B0?= =?UTF-8?q?=20=D0=BE=D0=BF=D0=B5=D1=80=D0=B0=D1=86=D0=B8=D0=B8=20(=D0=B4?= =?UTF-8?q?=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82=D1=8C,=20=D1=83=D0=B4?= =?UTF-8?q?=D0=B0=D0=BB=D0=B8=D1=82=D1=8C,=20=D0=BF=D0=BE=D0=BB=D1=83?= =?UTF-8?q?=D1=87=D0=B8=D1=82=D1=8C)=20=D0=B8=20=D1=81=D0=B4=D0=B5=D0=BB?= =?UTF-8?q?=D0=B0=D0=BB=20=D0=B8=D1=81=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=BD=D0=B0=20=D0=B7=D0=B0=D0=B3=D1=80=D1=83?= =?UTF-8?q?=D0=B7=D0=BA=D1=83=20=D0=B8=20=D0=B2=D1=8B=D0=B3=D1=80=D1=83?= =?UTF-8?q?=D0=B7=D0=BA=D1=83=20=D1=84=D0=B0=D0=B9=D0=BB=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 1 - .../CollectionType.cs | 3 +- .../CollectionGenericObjects/Garage.cs | 12 +- .../ICollectionGenericObjects.cs | 3 +- .../ListGenericObjects.cs | 71 +++------- .../MassivGenericObjects.cs | 101 +++++--------- .../StorageCollection.cs | 27 ++-- .../Exceptions/CollectionOverflowException.cs | 8 +- .../Exceptions/ObjectNotFoundException.cs | 8 +- .../PositionOutOfCollectionException.cs | 8 +- .../HoistingCrane/FormCarCollection.cs | 125 +++++++----------- 11 files changed, 121 insertions(+), 246 deletions(-) diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs index 1c50f33..e56d990 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs @@ -1,5 +1,4 @@ using HoistingCrane.Drawning; -using System; namespace HoistingCrane.CollectionGenericObjects { public abstract class AbstractCompany diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionType.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionType.cs index 22ffa84..93433c2 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionType.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionType.cs @@ -1,5 +1,4 @@ -using System; -namespace HoistingCrane.CollectionGenericObjects +namespace HoistingCrane.CollectionGenericObjects { public enum CollectionType { diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs index 0cf29d7..4927dd5 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs @@ -1,6 +1,5 @@ using HoistingCrane.Drawning; -using System; -using System.Collections.Specialized; +using HoistingCrane.Exceptions; namespace HoistingCrane.CollectionGenericObjects { @@ -36,9 +35,12 @@ namespace HoistingCrane.CollectionGenericObjects { if (arr?.Get(i) != null) { - arr?.Get(i)?.SetPictureSize(pictureWidth, pictureHeight); - arr?.Get(i)?.SetPosition(_placeSizeWidth * currentPosWidth + 25, _placeSizeHeight * currentPosHeight + 15); - + try + { + arr?.Get(i)?.SetPictureSize(pictureWidth, pictureHeight); + arr?.Get(i)?.SetPosition(_placeSizeWidth * currentPosWidth + 25, _placeSizeHeight * currentPosHeight + 15); + } + catch (ObjectNotFoundException) { } } if (currentPosWidth > 0) diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs index 04b8de7..ae99e89 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,5 +1,4 @@ -using System; -namespace HoistingCrane.CollectionGenericObjects +namespace HoistingCrane.CollectionGenericObjects { public interface ICollectionGenericObjects where T: class diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs index 73f740c..7503bb0 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs @@ -1,7 +1,4 @@ using HoistingCrane.Exceptions; -using System; -using System.CodeDom.Compiler; - namespace HoistingCrane.CollectionGenericObjects { public class ListGenericObjects : ICollectionGenericObjects where T : class @@ -45,72 +42,34 @@ namespace HoistingCrane.CollectionGenericObjects public T? Get(int position) { - try - { - if (position >= Count || position < 0) - { - throw new PositionOutOfCollectionException(position); - } - return list[position]; - } - catch (PositionOutOfCollectionException ex) - { - MessageBox.Show(ex.Message); - return null; - } + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + return list[position]; } - + public int Insert(T obj) { - try + if (Count == _maxCount) { - if (Count == _maxCount) throw new CollectionOverflowException(Count); - list.Add(obj); - return Count; - } - catch(CollectionOverflowException ex) - { - MessageBox.Show(ex.Message); - return -1; + throw new CollectionOverflowException(Count); } + list.Add(obj); + return Count; } public int Insert(T obj, int position) { - try - { - if (position < 0 || position >= _maxCount) throw new PositionOutOfCollectionException(position); - if (Count == _maxCount) throw new CollectionOverflowException(Count); - list.Insert(position, obj); - return position; - } - catch (CollectionOverflowException ex) - { - MessageBox.Show(ex.Message); - return -1; - } - catch (PositionOutOfCollectionException ex) - { - MessageBox.Show(ex.Message); - return -1; - } - + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + if (Count == _maxCount) throw new CollectionOverflowException(Count); + list.Insert(position, obj); + return position; } public T? Remove(int position) { - try - { - if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - T? temp = list[position]; - list.RemoveAt(position); - return temp; - } - catch (PositionOutOfCollectionException ex) - { - MessageBox.Show(ex.Message); - return null; - } + if (position < 0 || position >= list.Count) throw new PositionOutOfCollectionException(position); + T? temp = list[position]; + list.RemoveAt(position); + return temp; } public IEnumerable GetItems() diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs index 7680ae0..43df118 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs @@ -1,6 +1,4 @@ using HoistingCrane.Exceptions; -using System; - namespace HoistingCrane.CollectionGenericObjects { public class MassivGenericObjects : ICollectionGenericObjects where T : class @@ -40,96 +38,63 @@ namespace HoistingCrane.CollectionGenericObjects public T? Get(int position) { - try - { - if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - //if (arr[position] == null) throw new ObjectNotFoundException(position); - return arr[position]; - } - catch (PositionOutOfCollectionException ex) - { - MessageBox.Show(ex.Message); - return null; - } - //catch (ObjectNotFoundException ex) - //{ - // MessageBox.Show(ex.Message); - // return null; - //} - } - - public IEnumerable GetItems() - { - for(int i = 0; i < arr.Length; i++) - { - yield return arr[i]; - } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + return arr[position]; } public int Insert(T obj) { - try + int countObjectNotNull = 0; + for(int i = 0; i < Count; i++) { - if (arr.Count(x => x != null) == MaxCount) throw new CollectionOverflowException(Count); - return Insert(obj, 0); - } - catch(CollectionOverflowException ex) - { - MessageBox.Show(ex.Message); - return -1; + if (arr[i] != null) countObjectNotNull += 1; } + if(countObjectNotNull == MaxCount) throw new CollectionOverflowException(Count); + return Insert(obj, 0); } - public int Insert(T obj, int position) { - try + if (position < 0 || position >= Count) { - if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position); + throw new PositionOutOfCollectionException(position); + } + int copyPos = position - 1; + while (position < Count) + { if (arr[position] == null) { arr[position] = obj; return position; } - else - { - if (Insert(obj, position + 1) != -1) - { - return position; - } - if (Insert(obj, position - 1) != -1) - { - return position; - } - return -1; - } + position++; } - catch (PositionOutOfCollectionException ex) + while (copyPos > 0) { - MessageBox.Show(ex.Message); - return -1; + if (arr[copyPos] == null) + { + arr[copyPos] = obj; + return copyPos; + } + copyPos--; } + throw new CollectionOverflowException(Count); } public T? Remove(int position) { - try + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + if (arr[position] == null) throw new ObjectNotFoundException(position); + T? temp = arr[position]; + arr[position] = null; + return temp; + } + + public IEnumerable GetItems() + { + for (int i = 0; i < arr.Length; i++) { - if (position < 0 || position >= MaxCount) throw new PositionOutOfCollectionException(position); - if (arr[position] == null) throw new ObjectNotFoundException(position); - T? temp = arr[position]; - arr[position] = null; - return temp; - } - catch (ObjectNotFoundException ex) - { - MessageBox.Show(ex.Message); - return null; - } - catch (PositionOutOfCollectionException ex) - { - MessageBox.Show(ex.Message); - return null; + yield return arr[i]; } } } diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs index cb6a3f0..7ac7b49 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs @@ -1,8 +1,6 @@ using HoistingCrane.Drawning; using HoistingCrane.Exceptions; -using System; using System.Text; - namespace HoistingCrane.CollectionGenericObjects { public class StorageCollection where T : DrawningTrackedVehicle @@ -84,7 +82,7 @@ namespace HoistingCrane.CollectionGenericObjects { if (dict.Count == 0) { - throw new Exception("В хранилище отсутствуют коллекции для сохранения"); + throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -95,6 +93,7 @@ namespace HoistingCrane.CollectionGenericObjects using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); + foreach (KeyValuePair> value in dict) { StringBuilder sb = new(); @@ -105,7 +104,6 @@ namespace HoistingCrane.CollectionGenericObjects { continue; } - sb.Append(value.Key); sb.Append(_separatorForKeyValue); sb.Append(value.Value.GetCollectionType); @@ -124,31 +122,30 @@ namespace HoistingCrane.CollectionGenericObjects } writer.Write(sb); } - } } /// - // /// Загрузка информации по грузовикам в хранилище из файла - // /// - // /// Путь и имя файла - // /// true - загрузка прошла успешно, false - ошибка при загрузке данных + /// Загрузка информации по грузовикам в хранилище из файла + /// + /// + /// public void LoadData(string filename) { if (!File.Exists(filename)) { - throw new Exception("Файл не существует"); + throw new FileNotFoundException("Файл не существует"); } using (StreamReader fs = File.OpenText(filename)) { string str = fs.ReadLine(); if (str == null || str.Length == 0) { - throw new Exception("В файле не присутствуют данные"); + throw new InvalidOperationException("В файле не присутствуют данные"); } if (!str.StartsWith(_collectionKey)) { - throw new Exception("В файле неверные данные"); + throw new FormatException("В файле неверные данные"); } dict.Clear(); string strs = ""; @@ -163,7 +160,7 @@ namespace HoistingCrane.CollectionGenericObjects ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - throw new Exception("Не удалось создать коллекцию"); + throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); } collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); @@ -175,12 +172,12 @@ namespace HoistingCrane.CollectionGenericObjects { if (collection.Insert(crane) == -1) { - throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); } } catch(CollectionOverflowException ex) { - throw new Exception("Коллекция переполнена"); + throw new CollectionOverflowException("Коллекция переполнена", ex); } } } diff --git a/HoistingCrane/HoistingCrane/Exceptions/CollectionOverflowException.cs b/HoistingCrane/HoistingCrane/Exceptions/CollectionOverflowException.cs index da3c19f..44eaf0a 100644 --- a/HoistingCrane/HoistingCrane/Exceptions/CollectionOverflowException.cs +++ b/HoistingCrane/HoistingCrane/Exceptions/CollectionOverflowException.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.Serialization; -using System.Text; -using System.Threading.Tasks; - +using System.Runtime.Serialization; namespace HoistingCrane.Exceptions { [Serializable] diff --git a/HoistingCrane/HoistingCrane/Exceptions/ObjectNotFoundException.cs b/HoistingCrane/HoistingCrane/Exceptions/ObjectNotFoundException.cs index c833095..bd43581 100644 --- a/HoistingCrane/HoistingCrane/Exceptions/ObjectNotFoundException.cs +++ b/HoistingCrane/HoistingCrane/Exceptions/ObjectNotFoundException.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.Serialization; -using System.Text; -using System.Threading.Tasks; - +using System.Runtime.Serialization; namespace HoistingCrane.Exceptions { [Serializable] diff --git a/HoistingCrane/HoistingCrane/Exceptions/PositionOutOfCollectionException.cs b/HoistingCrane/HoistingCrane/Exceptions/PositionOutOfCollectionException.cs index e35263d..15796e2 100644 --- a/HoistingCrane/HoistingCrane/Exceptions/PositionOutOfCollectionException.cs +++ b/HoistingCrane/HoistingCrane/Exceptions/PositionOutOfCollectionException.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.Serialization; -using System.Text; -using System.Threading.Tasks; - +using System.Runtime.Serialization; namespace HoistingCrane.Exceptions { [Serializable] diff --git a/HoistingCrane/HoistingCrane/FormCarCollection.cs b/HoistingCrane/HoistingCrane/FormCarCollection.cs index 8fb3fa7..623ad8f 100644 --- a/HoistingCrane/HoistingCrane/FormCarCollection.cs +++ b/HoistingCrane/HoistingCrane/FormCarCollection.cs @@ -1,17 +1,7 @@ using HoistingCrane.CollectionGenericObjects; using HoistingCrane.Drawning; -using HoistingCrane.Entities; +using HoistingCrane.Exceptions; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; - namespace HoistingCrane { public partial class FormCarCollection : Form @@ -34,46 +24,13 @@ namespace HoistingCrane { panelCompanyTool.Enabled = false; } - private void CreateObject(string type) - { - DrawningTrackedVehicle drawning; - if (_company == null) return; - Random rand = new(); - switch (type) - { - case nameof(DrawningHoistingCrane): - drawning = new DrawningHoistingCrane(rand.Next(100, 300), rand.Next(1000, 3000), GetColor(rand), GetColor(rand), true, true); - break; - - case nameof(DrawningTrackedVehicle): - drawning = new DrawningTrackedVehicle(rand.Next(100, 300), rand.Next(1000, 3000), GetColor(rand)); - break; - default: - return; - } - if ((_company + drawning) != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - } - 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 buttonCreateHoistingCrane_Click(object sender, EventArgs e) { FormCarConfig form = new(); form.Show(); - form.AddEvent(SetCar); + form.AddEvent(SetCrane); } - private void SetCar(DrawningTrackedVehicle drawningTrackedVehicle) + private void SetCrane(DrawningTrackedVehicle drawningTrackedVehicle) { if (_company == null || drawningTrackedVehicle == null) return; try @@ -86,37 +43,53 @@ namespace HoistingCrane } else { - throw new Exception("Не удалось добавить объект. Заполнено максимальное количество ячеек"); + MessageBox.Show("Не удалось добавить объект"); + logger.LogInformation("Не удалось добавить корабль {ship} в коллекцию", drawningTrackedVehicle.GetType().Name); } } - catch (Exception ex) + catch (CollectionOverflowException ex) { - logger.LogInformation(ex.Message); - return; + MessageBox.Show("Ошибка переполнения коллекции"); + logger.LogError("Ошибка: {Message}", ex.Message); } } private void buttonDeleteCar_Click(object sender, EventArgs e) { - //if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return; - //if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) return; - //try - //{ - // int pos = Convert.ToInt32(maskedTextBox.Text); - // if ((_company - pos) != null) - // { - // MessageBox.Show("Объект удален!"); - // pictureBox.Image = _company.Show(); - // logger.LogInformation("Удален объект по позиции: {pos} ", pos); - // } - // else throw new Exception(); - //} - //catch(Exception ex) - //{ - // logger.LogInformation("Не удалось удалить объект по позиции: {pos}", Convert.ToInt32(maskedTextBox.Text)); - // return; - //} + if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) + { + return; + } + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + return; + } + try + { + int pos = Convert.ToInt32(maskedTextBox.Text); + if ((_company - pos) != null) + { + MessageBox.Show("Объект удален!"); + pictureBox.Image = _company.Show(); + logger.LogInformation("Удаление авто по индексу {pos}", pos); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + logger.LogInformation("Не удалось удалить авто из коллекции по индексу {pos}", pos); + } + } + catch (ObjectNotFoundException ex) + { + MessageBox.Show("Ошибка: отсутствует объект"); + logger.LogError("Ошибка: {Message}", ex.Message); + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show("Ошибка: неправильная позиция"); + logger.LogError("Ошибка: {Message}", ex.Message); + } } private void buttonRefresh_Click(object sender, EventArgs e) { @@ -162,20 +135,20 @@ namespace HoistingCrane { if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены"); return; } CollectionType collectionType = CollectionType.None; if (radioButtonMassive.Checked) { collectionType = CollectionType.Massive; - logger.LogInformation("Создана коллекция типа: {name}", collectionType); + logger.LogInformation("Создана коллекция типа: {name}, название: {name}", collectionType, textBoxCollectionName.Text); } else if (radioButtonList.Checked) { collectionType = CollectionType.List; - logger.LogInformation("Создана коллекция типа: {name}", collectionType); + logger.LogInformation("Создана коллекция типа: {name}, название: {name}", collectionType, textBoxCollectionName.Text); } _storageCollection.AddCollection(textBoxCollectionName.Text,collectionType);RerfreshListBoxItems(); } @@ -190,7 +163,7 @@ namespace HoistingCrane return; _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); RerfreshListBoxItems(); - logger.LogInformation("Коллекция успешно удалена"); + logger.LogInformation("Коллекция {name} успешно удалена", listBoxCollection.SelectedItem.ToString()); } private void buttonCreateCompany_Click(object sender, EventArgs e) { @@ -233,7 +206,7 @@ namespace HoistingCrane MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - catch (FileNotFoundException ex) + catch (Exception ex) { MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); logger.LogError("Ошибка: {Message}", ex.Message); @@ -253,11 +226,11 @@ namespace HoistingCrane try { _storageCollection.LoadData(openFileDialog.FileName); - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); RerfreshListBoxItems(); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); logger.LogInformation("Загрузка в файл: {filename}", saveFileDialog.FileName); } - catch(FileNotFoundException ex) + catch(Exception ex) { MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); logger.LogError("Ошибка: {Message}", ex.Message); From ea555cc89719b619e6234fee39543348883c3344 Mon Sep 17 00:00:00 2001 From: sqdselo <147947144+sqdselo@users.noreply.github.com> Date: Mon, 6 May 2024 23:02:05 +0400 Subject: [PATCH 7/9] =?UTF-8?q?=D0=93=D0=BE=D1=82=D0=BE=D0=B2=D0=B0=D1=8F?= =?UTF-8?q?=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 1 - .../HoistingCrane/FormCarCollection.cs | 13 ++++++----- .../HoistingCrane/HoistingCrane.csproj | 10 ++++----- HoistingCrane/HoistingCrane/Program.cs | 22 ++++++------------- HoistingCrane/HoistingCrane/nlog.config | 13 ----------- 5 files changed, 18 insertions(+), 41 deletions(-) delete mode 100644 HoistingCrane/HoistingCrane/nlog.config diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs index e56d990..fb26d02 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs @@ -40,7 +40,6 @@ namespace HoistingCrane.CollectionGenericObjects arr = array; arr.MaxCount = GetMaxCount; } - public static int operator +(AbstractCompany company, DrawningTrackedVehicle car) { return company.arr?.Insert(car) ?? -1; diff --git a/HoistingCrane/HoistingCrane/FormCarCollection.cs b/HoistingCrane/HoistingCrane/FormCarCollection.cs index 623ad8f..318a373 100644 --- a/HoistingCrane/HoistingCrane/FormCarCollection.cs +++ b/HoistingCrane/HoistingCrane/FormCarCollection.cs @@ -129,7 +129,6 @@ namespace HoistingCrane listBoxCollection.Items.Add(colName); } } - logger.LogInformation("Коллекция успешно обновлена"); } private void buttonCollectionAdd_Click(object sender, EventArgs e) { @@ -143,12 +142,12 @@ namespace HoistingCrane if (radioButtonMassive.Checked) { collectionType = CollectionType.Massive; - logger.LogInformation("Создана коллекция типа: {name}, название: {name}", collectionType, textBoxCollectionName.Text); + logger.LogInformation("Создана коллекция '{nameCol}' , название: {name}", collectionType, textBoxCollectionName.Text); } else if (radioButtonList.Checked) { collectionType = CollectionType.List; - logger.LogInformation("Создана коллекция типа: {name}, название: {name}", collectionType, textBoxCollectionName.Text); + logger.LogInformation("Создана коллекция '{nameCol}' , название: {name}", collectionType, textBoxCollectionName.Text); } _storageCollection.AddCollection(textBoxCollectionName.Text,collectionType);RerfreshListBoxItems(); } @@ -161,9 +160,13 @@ namespace HoistingCrane } if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return; + if (listBoxCollection.SelectedItem != null) + { + logger.LogInformation("Коллекция '{name}' успешно удалена", listBoxCollection.SelectedItem.ToString()); + } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); RerfreshListBoxItems(); - logger.LogInformation("Коллекция {name} успешно удалена", listBoxCollection.SelectedItem.ToString()); + } private void buttonCreateCompany_Click(object sender, EventArgs e) { @@ -187,8 +190,6 @@ namespace HoistingCrane } panelCompanyTool.Enabled = true; RerfreshListBoxItems(); - logger.LogInformation("Создана компания"); - } /// diff --git a/HoistingCrane/HoistingCrane/HoistingCrane.csproj b/HoistingCrane/HoistingCrane/HoistingCrane.csproj index 5f40a60..9b3b27e 100644 --- a/HoistingCrane/HoistingCrane/HoistingCrane.csproj +++ b/HoistingCrane/HoistingCrane/HoistingCrane.csproj @@ -15,6 +15,10 @@ + + + + @@ -32,10 +36,4 @@ - - - Always - - - \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/Program.cs b/HoistingCrane/HoistingCrane/Program.cs index c5abf19..562ee2d 100644 --- a/HoistingCrane/HoistingCrane/Program.cs +++ b/HoistingCrane/HoistingCrane/Program.cs @@ -1,37 +1,29 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using NLog.Extensions.Logging; +using Serilog; +using Serilog.Extensions.Logging; namespace HoistingCrane { 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(); ServiceCollection services = new(); ConfigureServices(services); using ServiceProvider serviceProvider = services.BuildServiceProvider(); Application.Run(serviceProvider.GetRequiredService()); - } - /// - /// DI - /// - /// private static void ConfigureServices(ServiceCollection services) { - services.AddSingleton().AddLogging(option => + // Serilog + Log.Logger = new LoggerConfiguration().WriteTo.File("E:\\myLog.log").CreateLogger(); + services.AddSingleton().AddLogging(builder => { - option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); + builder.AddSerilog(); }); } } -} \ No newline at end of file +} diff --git a/HoistingCrane/HoistingCrane/nlog.config b/HoistingCrane/HoistingCrane/nlog.config deleted file mode 100644 index 0c93951..0000000 --- a/HoistingCrane/HoistingCrane/nlog.config +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - \ No newline at end of file From 84b3e6f21e3ba4ea1febf7b8e096bd096cde82d5 Mon Sep 17 00:00:00 2001 From: sqdselo <147947144+sqdselo@users.noreply.github.com> Date: Mon, 6 May 2024 23:02:05 +0400 Subject: [PATCH 8/9] =?UTF-8?q?=D0=B4=D0=BE=D0=BF=D0=BA=D0=B0=D0=93=D0=BE?= =?UTF-8?q?=D1=82=D0=BE=D0=B2=D0=B0=D1=8F=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80?= =?UTF-8?q?=D0=B0=D1=82=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../HoistingCrane/FormCarCollection.cs | 10 ++++---- .../HoistingCrane/HoistingCrane.csproj | 5 +++- HoistingCrane/HoistingCrane/Program.cs | 24 ++++++++++++++----- HoistingCrane/HoistingCrane/serilog.json | 18 ++++++++++++++ ФайлДляЛабы.txt | 2 ++ 6 files changed, 48 insertions(+), 13 deletions(-) create mode 100644 HoistingCrane/HoistingCrane/serilog.json create mode 100644 ФайлДляЛабы.txt diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs index fb26d02..10711a6 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs @@ -30,7 +30,7 @@ namespace HoistingCrane.CollectionGenericObjects { get { - return (pictureWidth * pictureHeight) / (_placeSizeHeight * _placeSizeWidth)-2; + return (pictureWidth / _placeSizeWidth) * (pictureHeight / _placeSizeHeight); } } public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects array) diff --git a/HoistingCrane/HoistingCrane/FormCarCollection.cs b/HoistingCrane/HoistingCrane/FormCarCollection.cs index 318a373..bde17ab 100644 --- a/HoistingCrane/HoistingCrane/FormCarCollection.cs +++ b/HoistingCrane/HoistingCrane/FormCarCollection.cs @@ -44,7 +44,7 @@ namespace HoistingCrane else { MessageBox.Show("Не удалось добавить объект"); - logger.LogInformation("Не удалось добавить корабль {ship} в коллекцию", drawningTrackedVehicle.GetType().Name); + logger.LogInformation("Не удалось добавить кран {crane} в коллекцию", drawningTrackedVehicle.GetType().Name); } } catch (CollectionOverflowException ex) @@ -142,12 +142,12 @@ namespace HoistingCrane if (radioButtonMassive.Checked) { collectionType = CollectionType.Massive; - logger.LogInformation("Создана коллекция '{nameCol}' , название: {name}", collectionType, textBoxCollectionName.Text); + logger.LogInformation("Создана коллекция {nameCol} , название: {name}", collectionType, textBoxCollectionName.Text); } else if (radioButtonList.Checked) { collectionType = CollectionType.List; - logger.LogInformation("Создана коллекция '{nameCol}' , название: {name}", collectionType, textBoxCollectionName.Text); + logger.LogInformation("Создана коллекция {nameCol} , название: {name}", collectionType, textBoxCollectionName.Text); } _storageCollection.AddCollection(textBoxCollectionName.Text,collectionType);RerfreshListBoxItems(); } @@ -205,7 +205,7 @@ namespace HoistingCrane { _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); + logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName.ToString()); } catch (Exception ex) { @@ -229,7 +229,7 @@ namespace HoistingCrane _storageCollection.LoadData(openFileDialog.FileName); RerfreshListBoxItems(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - logger.LogInformation("Загрузка в файл: {filename}", saveFileDialog.FileName); + logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName.ToString()); } catch(Exception ex) { diff --git a/HoistingCrane/HoistingCrane/HoistingCrane.csproj b/HoistingCrane/HoistingCrane/HoistingCrane.csproj index 9b3b27e..3f2e375 100644 --- a/HoistingCrane/HoistingCrane/HoistingCrane.csproj +++ b/HoistingCrane/HoistingCrane/HoistingCrane.csproj @@ -13,8 +13,11 @@ + + - + + diff --git a/HoistingCrane/HoistingCrane/Program.cs b/HoistingCrane/HoistingCrane/Program.cs index 562ee2d..48fac59 100644 --- a/HoistingCrane/HoistingCrane/Program.cs +++ b/HoistingCrane/HoistingCrane/Program.cs @@ -1,8 +1,7 @@ +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Serilog; -using Serilog.Extensions.Logging; - namespace HoistingCrane { internal static class Program @@ -18,11 +17,24 @@ namespace HoistingCrane } private static void ConfigureServices(ServiceCollection services) { - // Serilog - Log.Logger = new LoggerConfiguration().WriteTo.File("E:\\myLog.log").CreateLogger(); - services.AddSingleton().AddLogging(builder => + + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) { - builder.AddSerilog(); + 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()); }); } } diff --git a/HoistingCrane/HoistingCrane/serilog.json b/HoistingCrane/HoistingCrane/serilog.json new file mode 100644 index 0000000..a8648e8 --- /dev/null +++ b/HoistingCrane/HoistingCrane/serilog.json @@ -0,0 +1,18 @@ + +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "log.log" + } + } + ], + "Properties": { + "Application": "Sample" + } + } +} diff --git a/ФайлДляЛабы.txt b/ФайлДляЛабы.txt new file mode 100644 index 0000000..f37cd75 --- /dev/null +++ b/ФайлДляЛабы.txt @@ -0,0 +1,2 @@ +CollectionsStorage +массив|Massive|25|EntityTrackedVehicle:100:100:White;EntityTrackedVehicle:100:100:Yellow;EntityTrackedVehicle:100:100:Purple;EntityHoistingCrane:100:100:Gray:Black:True:False;EntityTrackedVehicle:100:100:White;EntityTrackedVehicle:100:100:White;EntityHoistingCrane:100:100:Green:Black:False:False;EntityTrackedVehicle:100:100:Gray;EntityTrackedVehicle:100:100:Red;EntityHoistingCrane:100:100:White:Black:False:False;EntityHoistingCrane:100:100:Green:Blue:True:False;EntityHoistingCrane:100:100:Black:Black:True:True;EntityTrackedVehicle:100:100:White;EntityTrackedVehicle:100:100:Purple;EntityTrackedVehicle:100:100:Black;EntityTrackedVehicle:100:100:Blue;EntityTrackedVehicle:100:100:Gray;EntityTrackedVehicle:100:100:Red;EntityTrackedVehicle:100:100:Purple;EntityTrackedVehicle:100:100:Green;EntityTrackedVehicle:100:100:Purple;EntityTrackedVehicle:100:100:Yellow;EntityTrackedVehicle:100:100:Blue;EntityTrackedVehicle:100:100:Gray; \ No newline at end of file From e4d751e638c6e54565c8f4370dbc2e1579bd67dd Mon Sep 17 00:00:00 2001 From: Timur_Sharafutdinov Date: Mon, 13 May 2024 13:45:27 +0400 Subject: [PATCH 9/9] =?UTF-8?q?=D0=93=D0=BE=D1=82=D0=BE=D0=B2=D0=B0=D1=8F?= =?UTF-8?q?=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- HoistingCrane/HoistingCrane/serilog.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/HoistingCrane/HoistingCrane/serilog.json b/HoistingCrane/HoistingCrane/serilog.json index a8648e8..e76e9c8 100644 --- a/HoistingCrane/HoistingCrane/serilog.json +++ b/HoistingCrane/HoistingCrane/serilog.json @@ -15,4 +15,4 @@ "Application": "Sample" } } -} +} \ No newline at end of file