diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/AbstractCompany.cs b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/AbstractCompany.cs
index 582fdac..64bbfc8 100644
--- a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/AbstractCompany.cs
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/AbstractCompany.cs
@@ -32,7 +32,7 @@ public abstract class AbstractCompany
///
/// Вычисление максимального количества элементов, который можно разместить в окне
///
- private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
+ private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight))-1;
///
/// Конструктор
@@ -93,10 +93,15 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
- DrawingExcavatorEmpty? obj = _collection?.Get(i);
- obj?.DrawTransport(graphics);
+ try
+ {
+ DrawingExcavatorEmpty? obj = _collection?.Get(i);
+ obj?.DrawTransport(graphics);
+ }
+ catch (Exception) { }
}
+
return bitmap;
}
diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ExcavatorSharingServise.cs b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ExcavatorSharingServise.cs
index e21a92d..d3d7076 100644
--- a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ExcavatorSharingServise.cs
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ExcavatorSharingServise.cs
@@ -41,11 +41,12 @@ public class ExcavatorSharingServise : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
- if (_collection.Get(i) != null)
+ try
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
- _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 2);
+ _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 4);
}
+ catch (Exception) { }
if (curWidth > 0)
curWidth--;
else
diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs
index ade57f2..5daa78c 100644
--- a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs
@@ -37,14 +37,14 @@ public interface ICollectionGenericObjects
///
/// Позиция
/// true - удаление прошло удачно, false - удаление не удалось
- T Remove(int position);
+ T? Remove(int position);
///
/// Получение объекта по позиции
///
/// Позиция
/// Объект
- T? Get(int position);
+ T Get(int position);
///
/// получение типа коллекции
///
diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ListGenericObjects.cs b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ListGenericObjects.cs
index 6692272..377caf4 100644
--- a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ListGenericObjects.cs
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ListGenericObjects.cs
@@ -1,6 +1,8 @@
+using WinFormsAppExcavator.Exceptions;
namespace WinFormsAppExcavator.CollectionGenericObjects;
+
public class ListGenericObjects : ICollectionGenericObjects
where T : class
{
@@ -37,38 +39,30 @@ public class ListGenericObjects : ICollectionGenericObjects
{
_collection = new();
}
- public T? Get(int position)
+ public T Get(int position)
{
- // TODO проверка позиции
- if (position >= Count || position < 0) return null;
+ if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
- // TODO проверка, что не превышено максимальное количество элементов
- // TODO вставка в конец набора
- if (Count == _maxCount) return -1;
+ if (Count == _maxCount) throw new CollectionOverflowException();
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
- // TODO проверка, что не превышено максимальное количество элементов
- // TODO проверка позиции
- // TODO вставка по позиции
- if (Count == _maxCount) return -1;
- if (position >= Count || position < 0) return -1;
+ if (Count == _maxCount) throw new CollectionOverflowException(Count);
+ if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
}
- public T Remove(int position)
+ public T? Remove(int position)
{
- // TODO проверка позиции
- // TODO удаление объекта из списка
- if (position >= Count || position < 0) return null;
- T obj = _collection[position];
+ if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
+ T temp = _collection[position];
_collection.RemoveAt(position);
- return obj;
+ return temp;
}
public IEnumerable GetItems()
diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/MassiveGenericObjects.cs b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/MassiveGenericObjects.cs
index 5bbdb0f..f1afb56 100644
--- a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -1,4 +1,6 @@
+using WinFormsAppExcavator.Exceptions;
+
namespace WinFormsAppExcavator.CollectionGenericObjects;
///
/// параметризованный набор объектов
@@ -45,17 +47,16 @@ public class MassiveGenericObjects : ICollectionGenericObjects
_collection = Array.Empty();
}
- public T? Get(int position)
+ public T Get(int position)
{
- // TODO проверка позиции
if (position >= _collection.Length || position < 0)
- { return null; }
+ { throw new PositionOutOfCollectionException(position); }
+ if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
{
- // TODO вставка в свободное место набора
int index = 0;
while (index < _collection.Length)
{
@@ -67,18 +68,16 @@ public class MassiveGenericObjects : ICollectionGenericObjects
index++;
}
- return -1;
+ throw new CollectionOverflowException(Count);
+
}
public int Insert(T obj, int position)
{
- // TODO проверка позиции
- // TODO проверка, что элемент массива по этой позиции пустой, если нет, то
- // ищется свободное место после этой позиции и идет вставка туда
- // если нет после, ищем до
- // TODO вставка
if (position >= _collection.Length || position < 0)
- { return -1; }
+ {
+ throw new PositionOutOfCollectionException(position);
+ }
if (_collection[position]==null)
{
@@ -104,15 +103,16 @@ public class MassiveGenericObjects : ICollectionGenericObjects
return position;
}
}
- return -1;
+ throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
- // TODO проверка позиции
- // TODO удаление объекта из массива, присвоив элементу массива значение null
+
if (position >= _collection.Length || position < 0)
- { return null; }
+ {
+ throw new PositionOutOfCollectionException(position);}
+ if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position];
_collection[position] = null;
return obj;
diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/StorageCollection.cs b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/StorageCollection.cs
index 798a4c5..b6e0cb5 100644
--- a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/StorageCollection.cs
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/StorageCollection.cs
@@ -1,5 +1,6 @@
using System.Text;
using WinFormsAppExcavator.Drawings;
+using WinFormsAppExcavator.Exceptions;
namespace WinFormsAppExcavator.CollectionGenericObjects;
///
@@ -91,11 +92,11 @@ public class StorageCollection
/// Путь и имя файла
/// true - сохранение прошло успешно, false - ошибка при
///сохранении данных
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (_storages.Count == 0)
{
- return false;
+ throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
@@ -108,7 +109,6 @@ public class StorageCollection
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
- // не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
@@ -133,7 +133,6 @@ public class StorageCollection
}
}
- return true;
}
///
/// Загрузка информации по автомобилям в хранилище из файла
@@ -144,62 +143,77 @@ public class StorageCollection
{
if (!File.Exists(filename))
{
- return false;
+ throw new Exception("Файл не существует");
}
- using (StreamReader fs = File.OpenText(filename))
+
+ string bufferTextFromFile = "";
+ using (FileStream fs = new(filename, FileMode.Open))
{
- string str = fs.ReadLine();
- if (str == null || str.Length == 0)
+ byte[] b = new byte[fs.Length];
+ UTF8Encoding temp = new(true);
+ while (fs.Read(b, 0, b.Length) > 0)
{
- return false;
+ bufferTextFromFile += temp.GetString(b);
}
- if (!str.StartsWith(_collectionKey))
+ }
+
+ string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
+ if (strs == null || strs.Length == 0)
+ {
+ throw new Exception("В файле нет данных");
+ }
+
+ if (!strs[0].Equals(_collectionKey))
+ {
+ throw new Exception("В файле неверные данные");
+ }
+
+ _storages.Clear();
+ foreach (string data in strs)
+ {
+ string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
+ if (record.Length != 4)
{
- return false;
+ continue;
}
- _storages.Clear();
- string strs = "";
- while ((strs = fs.ReadLine()) != null)
+
+
+ CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
+ ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ??
+ throw new Exception("Не удалось определить тип коллекции:" + record[1]);
+ collection.MaxCount = Convert.ToInt32(record[2]);
+
+ string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
+ foreach (string elem in set)
{
- //по идее этого произойти не должно
- //if (strs == null)
- //{
- // return false;
- //}
- string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
- if (record.Length != 4)
+ if (elem?.CreateDrawningExcavatorEmpty() is T excavator)
{
- continue;
- }
- CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
- ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType);
- if (collection == null)
- {
- return false;
- }
- collection.MaxCount = Convert.ToInt32(record[2]);
- string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
- foreach (string elem in set)
- {
- if (elem?.CreateDrawningExcavatorEmpty() is T ship)
+ try
{
- if (collection.Insert(ship) == -1)
+ if (collection.Insert(excavator) != -1)
{
- return false;
+ throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
+ catch (CollectionOverflowException ex)
+ {
+ throw new Exception("Коллекция переполнена", ex);
+ }
}
- _storages.Add(record[0], collection);
}
- return true;
+
+ _storages.Add(record[0], collection);
}
+
+ return true;
}
- ///
- /// Создание коллекции по типу
- ///
- ///
- ///
- private static ICollectionGenericObjects?CreateCollection(CollectionType collectionType)
+
+ ///
+ /// Создание коллекции по типу
+ ///
+ ///
+ ///
+ private static ICollectionGenericObjects?CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/Exception/CollectionOverflowException.cs b/WinFormsAppExcavator/WinFormsAppExcavator/Exception/CollectionOverflowException.cs
new file mode 100644
index 0000000..36acabf
--- /dev/null
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/Exception/CollectionOverflowException.cs
@@ -0,0 +1,20 @@
+using System.Runtime.Serialization;
+
+namespace WinFormsAppExcavator.Exceptions;
+
+///
+/// Класс, описывающий ошибку переполнения коллекции
+///
+[Serializable]
+internal class CollectionOverflowException : ApplicationException
+{
+ public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
+
+ public CollectionOverflowException() : base() { }
+
+ public CollectionOverflowException(string message) : base(message) { }
+
+ public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
+
+ protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+}
\ No newline at end of file
diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/Exception/ObjectNotFoundException.cs b/WinFormsAppExcavator/WinFormsAppExcavator/Exception/ObjectNotFoundException.cs
new file mode 100644
index 0000000..3546ae8
--- /dev/null
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/Exception/ObjectNotFoundException.cs
@@ -0,0 +1,20 @@
+using System.Runtime.Serialization;
+
+namespace WinFormsAppExcavator.Exceptions;
+
+///
+/// Класс, описывающий ошибку, что по указанной позиции нет элемента
+///
+[Serializable]
+internal class ObjectNotFoundException : ApplicationException
+{
+ public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
+
+ public ObjectNotFoundException() : base() { }
+
+ public ObjectNotFoundException(string message) : base(message) { }
+
+ public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
+
+ protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+}
\ No newline at end of file
diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/Exception/PositionOutOfCollectionException.cs b/WinFormsAppExcavator/WinFormsAppExcavator/Exception/PositionOutOfCollectionException.cs
new file mode 100644
index 0000000..c7f3575
--- /dev/null
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/Exception/PositionOutOfCollectionException.cs
@@ -0,0 +1,21 @@
+using System.Runtime.Serialization;
+
+namespace WinFormsAppExcavator.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/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.Designer.cs b/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.Designer.cs
index ed185db..7a7d61f 100644
--- a/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.Designer.cs
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.Designer.cs
@@ -66,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
- groupBoxTools.Location = new Point(722, 28);
+ groupBoxTools.Location = new Point(642, 28);
groupBoxTools.Name = "groupBoxTools";
- groupBoxTools.Size = new Size(220, 527);
+ groupBoxTools.Size = new Size(220, 491);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@@ -82,14 +82,14 @@
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
- panelCompanyTools.Location = new Point(3, 327);
+ panelCompanyTools.Location = new Point(3, 314);
panelCompanyTools.Name = "panelCompanyTools";
- panelCompanyTools.Size = new Size(214, 197);
+ panelCompanyTools.Size = new Size(214, 174);
panelCompanyTools.TabIndex = 9;
//
// maskedTextBox
//
- maskedTextBox.Location = new Point(0, 62);
+ maskedTextBox.Location = new Point(3, 38);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(208, 27);
@@ -101,7 +101,7 @@
buttonAddExcavatorEmpty.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddExcavatorEmpty.Location = new Point(3, 3);
buttonAddExcavatorEmpty.Name = "buttonAddExcavatorEmpty";
- buttonAddExcavatorEmpty.Size = new Size(209, 53);
+ buttonAddExcavatorEmpty.Size = new Size(209, 29);
buttonAddExcavatorEmpty.TabIndex = 1;
buttonAddExcavatorEmpty.Text = "Добавление экскаватора простого";
buttonAddExcavatorEmpty.UseVisualStyleBackColor = true;
@@ -110,7 +110,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
- buttonGoToCheck.Location = new Point(3, 131);
+ buttonGoToCheck.Location = new Point(6, 107);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(206, 29);
buttonGoToCheck.TabIndex = 5;
@@ -121,7 +121,7 @@
// buttonRemoveExcavator
//
buttonRemoveExcavator.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
- buttonRemoveExcavator.Location = new Point(5, 95);
+ buttonRemoveExcavator.Location = new Point(5, 71);
buttonRemoveExcavator.Name = "buttonRemoveExcavator";
buttonRemoveExcavator.Size = new Size(206, 30);
buttonRemoveExcavator.TabIndex = 4;
@@ -132,7 +132,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
- buttonRefresh.Location = new Point(3, 166);
+ buttonRefresh.Location = new Point(3, 142);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(206, 27);
buttonRefresh.TabIndex = 6;
@@ -248,7 +248,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
- pictureBox.Size = new Size(722, 527);
+ pictureBox.Size = new Size(642, 491);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@@ -258,7 +258,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
- menuStrip.Size = new Size(942, 28);
+ menuStrip.Size = new Size(862, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
@@ -297,7 +297,7 @@
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
- ClientSize = new Size(942, 555);
+ ClientSize = new Size(862, 519);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.cs b/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.cs
index b42e105..2790486 100644
--- a/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.cs
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.cs
@@ -1,6 +1,8 @@
-using System.Windows.Forms;
+using Microsoft.Extensions.Logging;
+using System.Windows.Forms;
using WinFormsAppExcavator.CollectionGenericObjects;
using WinFormsAppExcavator.Drawings;
+using WinFormsAppExcavator.Exceptions;
namespace WinFormsAppExcavator;
///
@@ -15,14 +17,19 @@ public partial class FormExcavatorCollection : Form
///
/// компания
///
- AbstractCompany? _company = null;
+ private AbstractCompany? _company = null;
+
+ private readonly ILogger _logger;
+
///
/// Конструктор
///
- public FormExcavatorCollection()
+ public FormExcavatorCollection(ILogger logger)
{
InitializeComponent();
_storageCollection = new();
+ _logger = logger;
+ _logger.LogInformation("Форма загрузилась");
}
///
/// Выбор компании
@@ -42,8 +49,6 @@ public partial class FormExcavatorCollection : Form
private void ButtonAddExcavatorEmpty_Click(object sender, EventArgs e)
{
FormExcavatorConfig form = new();
- // TODO передать метод
-
form.Show();
form.AddEvent(SetExcavator);
@@ -54,19 +59,28 @@ public partial class FormExcavatorCollection : Form
///
private void SetExcavator(DrawingExcavatorEmpty? excavator)
{
- if (_company == null || excavator == null)
+ try
{
- return;
+ if (_company == null || excavator == null)
+ {
+ return;
+ }
+ if (_company + excavator != -1)
+ {
+ MessageBox.Show("Объект добавлен");
+ pictureBox.Image = _company.Show();
+ _logger.LogInformation("Добавлен объект: " + excavator.GetDataForSave());
+ }
}
-
- if (_company + excavator != -1)
- {
- MessageBox.Show("Объект добавлен");
- pictureBox.Image = _company.Show();
- }
- else
+ catch (ObjectNotFoundException) { }
+ catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
+ catch (PositionOutOfCollectionException ex) {
+ MessageBox.Show("Выход за границы коллекции");
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
///
@@ -82,20 +96,25 @@ public partial class FormExcavatorCollection : Form
return;
}
- if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
+ if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
- if (_company - pos != null)
+ try
{
- MessageBox.Show("Объект удален");
- pictureBox.Image = _company.Show();
+ if (_company - pos != null)
+ {
+ MessageBox.Show("Объект удален");
+ pictureBox.Image = _company.Show();
+ _logger.LogInformation("Удален объект по позиции " + pos);
+ }
}
- else
+ catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -113,26 +132,27 @@ public partial class FormExcavatorCollection : Form
DrawingExcavatorEmpty? excavator = null;
int counter = 100;
- while (excavator == null)
+ try
{
- excavator = _company.GetRandomObject();
- counter--;
- if (counter <= 0)
+ while (excavator == null)
{
- break;
+ excavator = _company.GetRandomObject();
+ counter--;
+ if (counter <= 0)
+ {
+ break;
+ }
}
+ FormExcavator form = new()
+ {
+ SetExcavator = excavator
+ };
+ form.ShowDialog();
}
-
- if (excavator == null)
+ catch (Exception ex)
{
- return;
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
-
- FormExcavator form = new()
- {
- SetExcavator = excavator
- };
- form.ShowDialog();
}
///
/// Кнопка обновления
@@ -161,17 +181,25 @@ public partial class FormExcavatorCollection : Form
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
- CollectionType collectionType = CollectionType.None;
- if (radioButtonMassive.Checked)
+ try
{
- collectionType = CollectionType.Massive;
+ CollectionType collectionType = CollectionType.None;
+ if (radioButtonMassive.Checked)
+ {
+ collectionType = CollectionType.Massive;
+ }
+ else if (radioButtonList.Checked)
+ {
+ collectionType = CollectionType.List;
+ }
+ _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
+ RerfreshListBoxItems();
+ _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
- else if (radioButtonList.Checked)
+ catch (Exception ex)
{
- collectionType = CollectionType.List;
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
- _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
- RerfreshListBoxItems();
}
///
@@ -202,12 +230,20 @@ public partial class FormExcavatorCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
- if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
+ try
{
- return;
+ if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
+ {
+ return;
+ }
+ _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
+ RerfreshListBoxItems();
+ _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
- _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
- RerfreshListBoxItems();
}
///
/// создание компании
@@ -247,15 +283,18 @@ public partial class FormExcavatorCollection : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storageCollection.SaveData(saveFileDialog.FileName))
+ try
{
+ _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);
}
}
@@ -270,18 +309,21 @@ public partial class FormExcavatorCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storageCollection.LoadData(openFileDialog.FileName))
+ try
{
- MessageBox.Show("Загрузка прошла успешно",
- "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _storageCollection.LoadData(openFileDialog.FileName);
+ MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
+ _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не загрузилось", "Результат",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
+
}
}
+
diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorConfig.cs b/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorConfig.cs
index a607fbb..f7b269e 100644
--- a/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorConfig.cs
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorConfig.cs
@@ -63,7 +63,7 @@ namespace WinFormsAppExcavator
///
/// Передаем информацию при нажатии на Labe
///
- ///
+ ///
///
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/Program.cs b/WinFormsAppExcavator/WinFormsAppExcavator/Program.cs
index 5dfa1c0..e2332a7 100644
--- a/WinFormsAppExcavator/WinFormsAppExcavator/Program.cs
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/Program.cs
@@ -1,4 +1,9 @@
-namespace WinFormsAppExcavator
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Serilog;
+using Microsoft.Extensions.Configuration;
+
+namespace WinFormsAppExcavator
{
internal static class Program
{
@@ -11,7 +16,30 @@
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
- Application.Run(new FormExcavatorCollection());
+ ServiceCollection services = new();
+ ConfigureServices(services);
+ using ServiceProvider servicesProvider = services.BuildServiceProvider();
+ Application.Run(servicesProvider.GetRequiredService());
+ }
+
+ private static void ConfigureServices(ServiceCollection services)
+ {
+ string[] path = Directory.GetCurrentDirectory().Split('\\');
+ string pathNeed = "";
+ for (int i = 0; i < path.Length - 3; i++)
+ {
+ pathNeed += path[i] + "\\";
+ }
+ services.AddSingleton()
+ .AddLogging(option =>
+ {
+ option.SetMinimumLevel(LogLevel.Information);
+ option.AddSerilog(new LoggerConfiguration()
+ .ReadFrom.Configuration(new ConfigurationBuilder()
+ .AddJsonFile($"{pathNeed}serilog.json")
+ .Build())
+ .CreateLogger());
+ });
}
}
}
\ No newline at end of file
diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/WinFormsAppExcavator.csproj b/WinFormsAppExcavator/WinFormsAppExcavator/WinFormsAppExcavator.csproj
index af03d74..84f16c4 100644
--- a/WinFormsAppExcavator/WinFormsAppExcavator/WinFormsAppExcavator.csproj
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/WinFormsAppExcavator.csproj
@@ -8,6 +8,17 @@
enable
+
+
+
+
+
+
+
+
+
+
+
True
diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/serilog.json b/WinFormsAppExcavator/WinFormsAppExcavator/serilog.json
new file mode 100644
index 0000000..a7878e1
--- /dev/null
+++ b/WinFormsAppExcavator/WinFormsAppExcavator/serilog.json
@@ -0,0 +1,15 @@
+{
+ "Serilog": {
+ "Using": [ "Serilog.Sinks.File" ],
+ "MinimumLevel": "Debug",
+ "WriteTo": [
+ {
+ "Name": "File",
+ "Args": { "path": "log.log" }
+ }
+ ],
+ "Properties": {
+ "Application": "Sample"
+ }
+ }
+}