PIBD-14_Arinina_M.A._Simple_LabWork06 #19

Closed
mara-1 wants to merge 2 commits from LabWork06 into LabWork05
15 changed files with 460 additions and 43 deletions

View File

@ -51,7 +51,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>

View File

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

View File

@ -13,12 +13,29 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _collection;
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
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>
@ -26,6 +43,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
_collection = new();
}
public T? Get(int position)
{
// TODO проверка позиции
@ -61,4 +79,11 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -16,8 +16,13 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@ -32,9 +37,10 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
@ -110,7 +116,14 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return myObject;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectBulldozer.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -11,7 +12,7 @@ namespace ProjectBulldozer.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T"></typeparam>
internal class StorageCollection<T>
where T : class
where T : DrawningTrackedMachine
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -23,6 +24,20 @@ internal class StorageCollection<T>
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
@ -40,19 +55,12 @@ internal class StorageCollection<T>
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (name == null || _storages.ContainsKey(name))
return;
switch (collectionType)
{
case CollectionType.None:
return;
case CollectionType.Massive:
_storages[name] = new MassiveGenericObjects<T>();
return;
case CollectionType.List:
_storages[name] = new ListGenericObjects<T>();
return;
}
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
}
@ -77,10 +85,134 @@ internal class StorageCollection<T>
get
{
// TODO Продумать логику получения объекта
if (name == null || !_storages.ContainsKey(name))
return null;
return _storages[name];
if (_storages.ContainsKey(name))
return _storages[name];
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
}
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);
Review

Записывать в файл можно сразу, без использования StringBuilder

Записывать в файл можно сразу, без использования StringBuilder
// не сохраняем пустые коллекции
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);
}
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith(_collectionKey))
{
return false;
}
_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)
{
return false;
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningMachine() is T machine)
{
if (collection.Insert(machine) == -1)
{
return false;
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}
/// <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

@ -26,6 +26,14 @@ public class DrawningBulldozer : DrawningTrackedMachine
additionalRihl);
}
/// <summary>
/// Конструктор для Extention
/// </summary>
/// <param name="bulldozer"></param>
public DrawningBulldozer(EntityBulldozer machine) : base(180, 140)
{
EntityTrackedMachine = new EntityBulldozer(machine.Speed, machine.Weight, machine.BodyColor, machine.AdditionalColor, machine.AdditionalOtval, machine.AdditionalRihl);
}
public override void DrawTransport(Graphics g)
{

View File

@ -97,6 +97,16 @@ public class DrawningTrackedMachine
}
/// <summary>
/// Конструктор для Extention
/// </summary>
/// <param name="trackedMachine"></param>
public DrawningTrackedMachine(EntityTrackedMachine machine) : this()
{
EntityTrackedMachine = new EntityTrackedMachine(machine.Speed, machine.Weight, machine.BodyColor);
}
/// <summary>
/// Установка границ поля
/// </summary>

View File

@ -0,0 +1,58 @@
using ProjectBulldozer.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer.Drawnings;
/// <summary>
/// Расширение для класса EntityCar
/// </summary>
public static class ExtentionDrawningMachine
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningTrackedMachine? CreateDrawningMachine(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTrackedMachine? machine = EntityBulldozer.CreateEntityBulldozer(strs);
if (machine != null)
{
return new DrawningBulldozer((EntityBulldozer)machine);
}
machine = EntityTrackedMachine.CreateEntityTrackedMachine(strs);
if (machine != null)
{
return new DrawningTrackedMachine(machine);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningTrackedMachine">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningTrackedMachine drawningTrackedMachine)
{
string[]? array = drawningTrackedMachine?.EntityTrackedMachine?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -1,11 +1,13 @@
namespace ProjectBulldozer.Entities;
using System.Net.Sockets;
namespace ProjectBulldozer.Entities;
/// <summary>
/// Класс-сущность "Бульдозер"
/// </summary>
public class EntityBulldozer : EntityTrackedMachine
{
public EntityBulldozer(int speed, double weight, Color bodyColor) : base(speed, weight, bodyColor)
{
}
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
@ -42,5 +44,30 @@ public class EntityBulldozer : EntityTrackedMachine
AdditionalRihl = additionalRihl;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityBulldozer), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,
AdditionalOtval.ToString(), AdditionalRihl.ToString()};
}
/// <summary>
/// Создание продвинутого объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityBulldozer? CreateEntityBulldozer(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityBulldozer))
{
return null;
}
return new EntityBulldozer(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]),
Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}
//сделано

View File

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

View File

@ -46,10 +46,17 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@ -59,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(749, 0);
groupBoxTools.Location = new Point(749, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(231, 665);
groupBoxTools.Size = new Size(231, 671);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -239,19 +246,62 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(749, 665);
pictureBox.Size = new Size(749, 671);
pictureBox.TabIndex = 5;
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(980, 28);
menuStrip.TabIndex = 6;
menuStrip.Text = "menuStrip1";
//
// файл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";
//
// FormMachineCollectoin
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(980, 665);
ClientSize = new Size(980, 699);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormMachineCollectoin";
Text = "Коллекция машин";
groupBoxTools.ResumeLayout(false);
@ -260,7 +310,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -283,5 +336,11 @@
private Panel panelStorage;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -53,7 +53,7 @@ public partial class FormMachineCollectoin : Form
/// <param name="e"></param>
public void ButtonAddMachine_Click(object sender, EventArgs e)
{
FormMachineConfig form = new();
form.AddEvent(SetMachine);
form.Show();
@ -262,5 +262,50 @@ public partial class FormMachineCollectoin : Form
RerfreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
}
else
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</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>
</root>

View File

@ -42,7 +42,7 @@ namespace ProjectBulldozer
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="carDelegate"></param>
/// <param name="machineDelegate"></param>
public void AddEvent(Action<DrawningTrackedMachine> machineDelegate)
{
MachineDelegate += machineDelegate;
@ -63,7 +63,7 @@ namespace ProjectBulldozer
/// <summary>
/// Передаем информацию при нажатии на Labe
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
@ -183,10 +183,8 @@ namespace ProjectBulldozer
/// <param name="e"></param>
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_machine.EntityTrackedMachine is EntityBulldozer _bulldozer)
{
if (_machine != null && _machine.EntityTrackedMachine is EntityBulldozer _bulldozer)
_bulldozer.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
}