7 Commits

22 changed files with 704 additions and 129 deletions

View File

@@ -32,7 +32,7 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight))-1;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@@ -45,7 +45,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.SetMaxCount = GetMaxCount; _collection.MaxCount = GetMaxCount;
} }
/// <summary> /// <summary>
@@ -92,10 +92,15 @@ public abstract class AbstractCompany
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{ {
DrawingExcavatorEmpty? obj = _collection?.Get(i); DrawingExcavatorEmpty? obj = _collection?.Get(i);
obj?.DrawTransport(graphics); obj?.DrawTransport(graphics);
} }
catch (Exception) { }
}
return bitmap; return bitmap;
} }

View File

@@ -41,11 +41,12 @@ public class ExcavatorSharingServise : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{ {
if (_collection.Get(i) != null) try
{ {
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _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) if (curWidth > 0)
curWidth--; curWidth--;
else else

View File

@@ -15,7 +15,7 @@ public interface ICollectionGenericObjects<T>
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int SetMaxCount { set; } int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
@@ -37,12 +37,22 @@ public interface ICollectionGenericObjects<T>
/// </summary> /// </summary>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns> /// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T Remove(int position); T? Remove(int position);
/// <summary> /// <summary>
/// Получение объекта по позиции /// Получение объекта по позиции
/// </summary> /// </summary>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>Объект</returns> /// <returns>Объект</returns>
T? Get(int position); T Get(int position);
/// <summary>
/// получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// получение объектов коллекции по одному
/// </summary>
/// <returns></returns>
IEnumerable<T?> GetItems();
} }

View File

@@ -1,4 +1,7 @@
namespace WinFormsAppExcavator.CollectionGenericObjects; 
using WinFormsAppExcavator.Exceptions;
namespace WinFormsAppExcavator.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T> public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
@@ -12,7 +15,23 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// </summary> /// </summary>
private int _maxCount; private int _maxCount;
public int Count => _collection.Count; public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } public int MaxCount
{
get
{
return Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -20,37 +39,37 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{ {
_collection = new(); _collection = new();
} }
public T? Get(int position) public T Get(int position)
{ {
// TODO проверка позиции if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (position >= Count || position < 0) return null;
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
// TODO проверка, что не превышено максимальное количество элементов if (Count == _maxCount) throw new CollectionOverflowException();
// TODO вставка в конец набора
if (Count == _maxCount) return -1;
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
// TODO проверка, что не превышено максимальное количество элементов if (Count == _maxCount) throw new CollectionOverflowException(Count);
// TODO проверка позиции if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
// TODO вставка по позиции
if (Count == _maxCount) return -1;
if (position >= Count || position < 0) return -1;
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
public T Remove(int position) public T? Remove(int position)
{ {
// TODO проверка позиции if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
// TODO удаление объекта из списка T temp = _collection[position];
if (position >= Count || position < 0) return null;
T obj = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return obj; return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i=0; i<Count; i++)
{
yield return _collection[i];
}
} }
} }

View File

@@ -1,4 +1,7 @@
namespace WinFormsAppExcavator.CollectionGenericObjects; 
using WinFormsAppExcavator.Exceptions;
namespace WinFormsAppExcavator.CollectionGenericObjects;
/// <summary> /// <summary>
/// параметризованный набор объектов /// параметризованный набор объектов
/// </summary> /// </summary>
@@ -12,8 +15,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
private T?[] _collection; private T?[] _collection;
public int Count => _collection.Length; public int Count => _collection.Length;
public int SetMaxCount public int MaxCount
{ get
{ {
return _collection.Length;
}
set set
{ {
if (value > 0) if (value > 0)
@@ -30,6 +37,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -38,17 +47,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection = Array.Empty<T?>(); _collection = Array.Empty<T?>();
} }
public T? Get(int position) public T Get(int position)
{ {
// TODO проверка позиции
if (position >= _collection.Length || position < 0) if (position >= _collection.Length || position < 0)
{ return null; } { throw new PositionOutOfCollectionException(position); }
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
// TODO вставка в свободное место набора
int index = 0; int index = 0;
while (index < _collection.Length) while (index < _collection.Length)
{ {
@@ -60,18 +68,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
index++; index++;
} }
return -1; throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
// TODO проверка позиции
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO вставка
if (position >= _collection.Length || position < 0) if (position >= _collection.Length || position < 0)
{ return -1; } {
throw new PositionOutOfCollectionException(position);
}
if (_collection[position]==null) if (_collection[position]==null)
{ {
@@ -97,17 +103,26 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return position; return position;
} }
} }
return -1; throw new CollectionOverflowException(Count);
} }
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0) if (position >= _collection.Length || position < 0)
{ return null; } {
throw new PositionOutOfCollectionException(position);}
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position]; T obj = _collection[position];
_collection[position] = null; _collection[position] = null;
return obj; return obj;
} }
public IEnumerable<T?> GetItems()
{
for (int i=0; i<_collection.Length;i++)
{
yield return _collection[i];
}
}
} }

View File

@@ -1,10 +1,14 @@
namespace WinFormsAppExcavator.CollectionGenericObjects; using System.Text;
using WinFormsAppExcavator.Drawings;
using WinFormsAppExcavator.Exceptions;
namespace WinFormsAppExcavator.CollectionGenericObjects;
/// <summary> /// <summary>
/// класс-хранилище /// класс-хранилище
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public class StorageCollection<T> public class StorageCollection<T>
where T : class where T : DrawingExcavatorEmpty
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
@@ -61,7 +65,148 @@ public class StorageCollection<T>
// TODO Продумать логику получения объекта // TODO Продумать логику получения объекта
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(name))
return _storages[name]; return _storages[name];
return null; return null;
}
}
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при
///сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке
///данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
throw new Exception("В файле неверные данные");
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningExcavatorEmpty() is T excavator)
{
try
{
if (collection.Insert(excavator) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
} }
} }
} }
_storages.Add(record[0], collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>?CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@@ -7,6 +7,8 @@ namespace WinFormsAppExcavator.Drawings;
/// </summary> /// </summary>
public class DrawingExcavator : DrawingExcavatorEmpty public class DrawingExcavator : DrawingExcavatorEmpty
{ {
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -23,6 +25,11 @@ public class DrawingExcavator : DrawingExcavatorEmpty
} }
public DrawingExcavator(EntityExcavator excavator) : base(100,90)
{
EntityExcavatorEmpty = new EntityExcavator(excavator.Speed, excavator.Weight, excavator.BodyColor, excavator.AdditionalColor, excavator.Bucket, excavator.Support, excavator.BulldozerDump);
}
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {
if (EntityExcavatorEmpty == null || EntityExcavatorEmpty is not EntityExcavator entityExcavator || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityExcavatorEmpty == null || EntityExcavatorEmpty is not EntityExcavator entityExcavator || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@@ -1,15 +1,9 @@
using System; using WinFormsAppExcavator.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinFormsAppExcavator.Entity;
namespace WinFormsAppExcavator.Drawings; namespace WinFormsAppExcavator.Drawings;
public class DrawingExcavatorEmpty public class DrawingExcavatorEmpty
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
/// </summary> /// </summary>
@@ -35,6 +29,8 @@ public class DrawingExcavatorEmpty
/// </summary> /// </summary>
protected int? _startPosY; protected int? _startPosY;
/// <summary> /// <summary>
/// Ширина прорисовки экскаватора /// Ширина прорисовки экскаватора
/// </summary> /// </summary>
@@ -99,6 +95,13 @@ public class DrawingExcavatorEmpty
} }
public DrawingExcavatorEmpty(EntityExcavatorEmpty excavator) : this()
{
EntityExcavatorEmpty = new EntityExcavatorEmpty(excavator.Speed, excavator.Weight, excavator.BodyColor);
}
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
/// </summary> /// </summary>

View File

@@ -0,0 +1,46 @@
using WinFormsAppExcavator.Entity;
namespace WinFormsAppExcavator.Drawings;
/// <summary>
/// расширение для класса EntityExcavator
/// </summary>
public static class ExtentionDrawningExcavatorEmpty
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawingExcavatorEmpty? CreateDrawningExcavatorEmpty(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityExcavatorEmpty? excavator = EntityExcavator.CreateEntityExcavator(strs);
if (excavator != null)
{
return new DrawingExcavator((EntityExcavator)excavator);
}
excavator = EntityExcavatorEmpty.CreateEntityExcavatorEmpty(strs);
if (excavator != null)
{
return new DrawingExcavatorEmpty(excavator);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingExcavatorEmpty drawningExcavatorEmpty)
{
string[]? array = drawningExcavatorEmpty?.EntityExcavatorEmpty?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -52,6 +52,32 @@ public class EntityExcavator : EntityExcavatorEmpty
BulldozerDump = bulldozerDump; BulldozerDump = bulldozerDump;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityExcavator), Speed.ToString(), Weight.ToString(), BodyColor.Name,
AdditionalColor.Name, Bucket.ToString(), Support.ToString(), BulldozerDump.ToString()};
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityExcavator? CreateEntityExcavator(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityExcavator))
{
return null;
}
return new EntityExcavator(Convert.ToInt32(strs[1]),
Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]),
Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
}
} }

View File

@@ -48,4 +48,28 @@ public class EntityExcavatorEmpty
Weight = weight; Weight = weight;
BodyColor = bodyColor; BodyColor = bodyColor;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityExcavatorEmpty), Speed.ToString(),Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityExcavatorEmpty? CreateEntityExcavatorEmpty(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityExcavatorEmpty))
{
return null;
}
return new EntityExcavatorEmpty(Convert.ToInt32(strs[1]),Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
} }

View File

@@ -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) { }
}

View File

@@ -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) { }
}

View File

@@ -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) { }
}

View File

@@ -46,10 +46,17 @@
labelCollectionName = new Label(); labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@@ -59,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(722, 0); groupBoxTools.Location = new Point(642, 28);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(220, 555); groupBoxTools.Size = new Size(220, 491);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
@@ -75,14 +82,14 @@
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 324); panelCompanyTools.Location = new Point(3, 314);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(214, 228); panelCompanyTools.Size = new Size(214, 174);
panelCompanyTools.TabIndex = 9; panelCompanyTools.TabIndex = 9;
// //
// maskedTextBox // maskedTextBox
// //
maskedTextBox.Location = new Point(3, 96); maskedTextBox.Location = new Point(3, 38);
maskedTextBox.Mask = "00"; maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(208, 27); maskedTextBox.Size = new Size(208, 27);
@@ -92,9 +99,9 @@
// buttonAddExcavatorEmpty // buttonAddExcavatorEmpty
// //
buttonAddExcavatorEmpty.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddExcavatorEmpty.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddExcavatorEmpty.Location = new Point(5, 0); buttonAddExcavatorEmpty.Location = new Point(3, 3);
buttonAddExcavatorEmpty.Name = "buttonAddExcavatorEmpty"; buttonAddExcavatorEmpty.Name = "buttonAddExcavatorEmpty";
buttonAddExcavatorEmpty.Size = new Size(209, 53); buttonAddExcavatorEmpty.Size = new Size(209, 29);
buttonAddExcavatorEmpty.TabIndex = 1; buttonAddExcavatorEmpty.TabIndex = 1;
buttonAddExcavatorEmpty.Text = "Добавление экскаватора простого"; buttonAddExcavatorEmpty.Text = "Добавление экскаватора простого";
buttonAddExcavatorEmpty.UseVisualStyleBackColor = true; buttonAddExcavatorEmpty.UseVisualStyleBackColor = true;
@@ -103,7 +110,7 @@
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(5, 163); buttonGoToCheck.Location = new Point(6, 107);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(206, 29); buttonGoToCheck.Size = new Size(206, 29);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
@@ -114,7 +121,7 @@
// buttonRemoveExcavator // buttonRemoveExcavator
// //
buttonRemoveExcavator.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveExcavator.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveExcavator.Location = new Point(5, 127); buttonRemoveExcavator.Location = new Point(5, 71);
buttonRemoveExcavator.Name = "buttonRemoveExcavator"; buttonRemoveExcavator.Name = "buttonRemoveExcavator";
buttonRemoveExcavator.Size = new Size(206, 30); buttonRemoveExcavator.Size = new Size(206, 30);
buttonRemoveExcavator.TabIndex = 4; buttonRemoveExcavator.TabIndex = 4;
@@ -125,7 +132,7 @@
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(5, 198); buttonRefresh.Location = new Point(3, 142);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(206, 27); buttonRefresh.Size = new Size(206, 27);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
@@ -239,19 +246,62 @@
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(722, 555); pictureBox.Size = new Size(642, 491);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(862, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormExcavatorCollection // FormExcavatorCollection
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(942, 555); ClientSize = new Size(862, 519);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormExcavatorCollection"; Name = "FormExcavatorCollection";
Text = "Коллекция экскаваторов"; Text = "Коллекция экскаваторов";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
@@ -260,7 +310,10 @@
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@@ -283,5 +336,11 @@
private Button buttonCollectionDel; private Button buttonCollectionDel;
private ListBox listBoxCollection; private ListBox listBoxCollection;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
} }
} }

View File

@@ -1,5 +1,8 @@
using WinFormsAppExcavator.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using System.Windows.Forms;
using WinFormsAppExcavator.CollectionGenericObjects;
using WinFormsAppExcavator.Drawings; using WinFormsAppExcavator.Drawings;
using WinFormsAppExcavator.Exceptions;
namespace WinFormsAppExcavator; namespace WinFormsAppExcavator;
/// <summary> /// <summary>
@@ -14,14 +17,19 @@ public partial class FormExcavatorCollection : Form
/// <summary> /// <summary>
/// компания /// компания
/// </summary> /// </summary>
AbstractCompany? _company = null; private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormExcavatorCollection() public FormExcavatorCollection(ILogger<FormExcavatorCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
/// <summary> /// <summary>
/// Выбор компании /// Выбор компании
@@ -41,8 +49,6 @@ public partial class FormExcavatorCollection : Form
private void ButtonAddExcavatorEmpty_Click(object sender, EventArgs e) private void ButtonAddExcavatorEmpty_Click(object sender, EventArgs e)
{ {
FormExcavatorConfig form = new(); FormExcavatorConfig form = new();
// TODO передать метод
form.Show(); form.Show();
form.AddEvent(SetExcavator); form.AddEvent(SetExcavator);
@@ -52,20 +58,29 @@ public partial class FormExcavatorCollection : Form
/// </summary> /// </summary>
/// <param name="excavator"></param> /// <param name="excavator"></param>
private void SetExcavator(DrawingExcavatorEmpty? excavator) private void SetExcavator(DrawingExcavatorEmpty? excavator)
{
try
{ {
if (_company == null || excavator == null) if (_company == null || excavator == null)
{ {
return; return;
} }
if (_company + excavator != -1) if (_company + excavator != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + excavator.GetDataForSave());
} }
else }
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex) {
MessageBox.Show("Выход за границы коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
/// <summary> /// <summary>
@@ -81,20 +96,25 @@ public partial class FormExcavatorCollection : Form
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBox.Text); int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
if (_company - pos != null) if (_company - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
} }
else }
catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@@ -112,6 +132,8 @@ public partial class FormExcavatorCollection : Form
DrawingExcavatorEmpty? excavator = null; DrawingExcavatorEmpty? excavator = null;
int counter = 100; int counter = 100;
try
{
while (excavator == null) while (excavator == null)
{ {
excavator = _company.GetRandomObject(); excavator = _company.GetRandomObject();
@@ -121,18 +143,17 @@ public partial class FormExcavatorCollection : Form
break; break;
} }
} }
if (excavator == null)
{
return;
}
FormExcavator form = new() FormExcavator form = new()
{ {
SetExcavator = excavator SetExcavator = excavator
}; };
form.ShowDialog(); form.ShowDialog();
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary> /// <summary>
/// Кнопка обновления /// Кнопка обновления
/// </summary> /// </summary>
@@ -160,6 +181,8 @@ public partial class FormExcavatorCollection : Form
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
try
{
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
{ {
@@ -171,6 +194,12 @@ public partial class FormExcavatorCollection : Form
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
/// <summary> /// <summary>
@@ -201,12 +230,20 @@ public partial class FormExcavatorCollection : Form
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
/// <summary> /// <summary>
/// создание компании /// создание компании
@@ -237,5 +274,56 @@ public partial class FormExcavatorCollection : Form
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
}

View File

@@ -117,4 +117,16 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>145, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>310, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>61</value>
</metadata>
</root> </root>

View File

@@ -170,7 +170,7 @@
// //
// panelGreen // panelGreen
// //
panelGreen.BackColor = Color.FromArgb(0, 192, 0); panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(74, 36); panelGreen.Location = new Point(74, 36);
panelGreen.Name = "panelGreen"; panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(35, 33); panelGreen.Size = new Size(35, 33);

View File

@@ -63,7 +63,7 @@ namespace WinFormsAppExcavator
/// <summary> /// <summary>
/// Передаем информацию при нажатии на Labe /// Передаем информацию при нажатии на Labe
/// </summary> /// </summary>
/// <param name="sender"></param> /// <palabelSimpleObjectram name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e) private void LabelObject_MouseDown(object sender, MouseEventArgs e)

View File

@@ -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 internal static class Program
{ {
@@ -11,7 +16,30 @@
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); 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());
});
} }
} }
} }

View File

@@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </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> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}