Лабораторная работа №7
This commit is contained in:
parent
b676330c29
commit
90cde95aba
@ -32,7 +32,7 @@ public abstract class AbstractCompany
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight))-1;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@ -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;
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
|
@ -37,14 +37,14 @@ public interface ICollectionGenericObjects<T>
|
||||
/// </summary>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
|
||||
T Remove(int position);
|
||||
T? Remove(int position);
|
||||
|
||||
/// <summary>
|
||||
/// Получение объекта по позиции
|
||||
/// </summary>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <returns>Объект</returns>
|
||||
T? Get(int position);
|
||||
T Get(int position);
|
||||
/// <summary>
|
||||
/// получение типа коллекции
|
||||
/// </summary>
|
||||
|
@ -1,6 +1,8 @@
|
||||
|
||||
using WinFormsAppExcavator.Exceptions;
|
||||
namespace WinFormsAppExcavator.CollectionGenericObjects;
|
||||
|
||||
|
||||
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
{
|
||||
@ -37,38 +39,30 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
{
|
||||
_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<T?> GetItems()
|
||||
|
@ -1,4 +1,6 @@
|
||||
|
||||
using WinFormsAppExcavator.Exceptions;
|
||||
|
||||
namespace WinFormsAppExcavator.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
/// параметризованный набор объектов
|
||||
@ -45,17 +47,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
_collection = Array.Empty<T?>();
|
||||
}
|
||||
|
||||
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<T> : ICollectionGenericObjects<T>
|
||||
|
||||
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<T> : ICollectionGenericObjects<T>
|
||||
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;
|
||||
|
@ -1,5 +1,6 @@
|
||||
using System.Text;
|
||||
using WinFormsAppExcavator.Drawings;
|
||||
using WinFormsAppExcavator.Exceptions;
|
||||
|
||||
namespace WinFormsAppExcavator.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
@ -91,11 +92,11 @@ public class StorageCollection<T>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при
|
||||
///сохранении данных</returns>
|
||||
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<T>
|
||||
{
|
||||
StringBuilder sb = new();
|
||||
sb.Append(Environment.NewLine);
|
||||
// не сохраняем пустые коллекции
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
@ -133,7 +133,6 @@ public class StorageCollection<T>
|
||||
}
|
||||
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
@ -144,62 +143,77 @@ public class StorageCollection<T>
|
||||
{
|
||||
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<T>? collection = StorageCollection<T>.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<T>? collection = StorageCollection<T>.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;
|
||||
}
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>?CreateCollection(CollectionType collectionType)
|
||||
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>?CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
return collectionType switch
|
||||
{
|
||||
|
@ -0,0 +1,20 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace WinFormsAppExcavator.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку переполнения коллекции
|
||||
/// </summary>
|
||||
[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) { }
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace WinFormsAppExcavator.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
|
||||
/// </summary>
|
||||
[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) { }
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace WinFormsAppExcavator.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку выхода за границы коллекции
|
||||
/// </summary>
|
||||
[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) { }
|
||||
}
|
||||
|
@ -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);
|
||||
|
@ -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;
|
||||
/// <summary>
|
||||
@ -15,14 +17,19 @@ public partial class FormExcavatorCollection : Form
|
||||
/// <summary>
|
||||
/// компания
|
||||
/// </summary>
|
||||
AbstractCompany? _company = null;
|
||||
private AbstractCompany? _company = null;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormExcavatorCollection()
|
||||
public FormExcavatorCollection(ILogger<FormExcavatorCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
_logger.LogInformation("Форма загрузилась");
|
||||
}
|
||||
/// <summary>
|
||||
/// Выбор компании
|
||||
@ -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
|
||||
/// <param name="excavator"></param>
|
||||
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);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -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();
|
||||
}
|
||||
/// <summary>
|
||||
/// Кнопка обновления
|
||||
@ -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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -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();
|
||||
}
|
||||
/// <summary>
|
||||
/// создание компании
|
||||
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -63,7 +63,7 @@ namespace WinFormsAppExcavator
|
||||
/// <summary>
|
||||
/// Передаем информацию при нажатии на Labe
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <palabelSimpleObjectram name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
|
||||
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
|
||||
|
@ -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<FormExcavatorCollection>());
|
||||
}
|
||||
|
||||
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<FormExcavatorCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(new ConfigurationBuilder()
|
||||
.AddJsonFile($"{pathNeed}serilog.json")
|
||||
.Build())
|
||||
.CreateLogger());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -8,6 +8,17 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
15
WinFormsAppExcavator/WinFormsAppExcavator/serilog.json
Normal file
15
WinFormsAppExcavator/WinFormsAppExcavator/serilog.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Debug",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": { "path": "log.log" }
|
||||
}
|
||||
],
|
||||
"Properties": {
|
||||
"Application": "Sample"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user