ISEbd-12_Pravednikova_D._O._LabWork06/Simple #6

Closed
Darya wants to merge 3 commits from LabWork06 into LabWork05
13 changed files with 433 additions and 33 deletions

View File

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

View File

@ -15,7 +15,7 @@ public interface ICollectionGenericObjects<T>
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
@ -45,4 +45,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

@ -1,4 +1,5 @@
namespace Excavator.CollectionGenericObjects;

namespace Excavator.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
@ -18,7 +19,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount { get { return _collection.Count; } set { if (value > 0) { _maxCount = value; } } }
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
@ -57,5 +60,11 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return pos;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -1,4 +1,5 @@
namespace Excavator.CollectionGenericObjects;

namespace Excavator.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@ -14,8 +15,12 @@ public 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,6 +37,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@ -90,4 +97,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return drawningTrackedVehicle;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; i++)
{
yield return _collection[i];
}
}
}

View File

@ -1,11 +1,13 @@
namespace Excavator.CollectionGenericObjects;
using Excavator.Drawnings;
using System.Text;
namespace Excavator.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningTrackedVehicle
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -32,18 +34,16 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (name == null || _storages.ContainsKey(name)) { return; }
switch (collectionType)
if (string.IsNullOrEmpty(name)) return;
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return;
if (collectionType == CollectionType.Massive)
{
case CollectionType.None:
return;
case CollectionType.Massive:
_storages[name] = new MassiveGenericObjects<T>();
return;
case CollectionType.List:
_storages[name] = new ListGenericObjects<T>();
return;
_storages[name] = new MassiveGenericObjects<T>();
}
else if (collectionType == CollectionType.List)
{
_storages[name] = new ListGenericObjects<T>();
}
}
@ -71,4 +71,143 @@ public class StorageCollection<T>
}
}
/// <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 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)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
writer.Write(data);
writer.Write(_separatorItems);
}
}
}
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 reader = File.OpenText(filename))
{
string? str = reader.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith(_collectionKey))
{
return false;
}
_storages.Clear();
string? strs = "";
while ((strs = reader.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?.CreateDrawningTrackedVehicle() is T car)
{
if (collection.Insert(car) == -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

@ -9,6 +9,18 @@ namespace Excavator.Drawnings;
/// </summary>
public class DrawningExcavator : DrawningTrackedVehicle
{
private EntityExcavator car;
public DrawningExcavator(EntityTrackedVehicle car) : base(car)
{
EntityTrackedVehicle = car;
}
/// <summary>
/// Конструктор
/// </summary>

View File

@ -33,6 +33,7 @@ public class DrawningTrackedVehicle
/// Верхняя кооридната прорисовки экскаватора
/// </summary>
protected int? _startPosY;
private EntityTrackedVehicle car;
/// <summary>
/// Ширина прорисовки экскаватора
@ -106,6 +107,13 @@ public class DrawningTrackedVehicle
}
public DrawningTrackedVehicle(EntityTrackedVehicle car) : this()
{
EntityTrackedVehicle = car;
}
/// <summary>

View File

@ -0,0 +1,46 @@
using Excavator.Entities;
namespace Excavator.Drawnings;
public static class ExtentionDrawningTrackedVehicle
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningTrackedVehicle? CreateDrawningTrackedVehicle(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTrackedVehicle? car = EntityExcavator.CreateEntityExcavator(strs);
if (car != null)
{
return new DrawningExcavator(car);
}
car = EntityTrackedVehicle.CreateEntityTrackedVehicle(strs);
if (car != null)
{
return new DrawningTrackedVehicle(car);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningTrackedVehicle">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningTrackedVehicle drawningTrackedVehicle)
{
string[]? array = drawningTrackedVehicle?.EntityTrackedVehicle?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -48,4 +48,28 @@ public class EntityExcavator : EntityTrackedVehicle
Bucket = bucket;
Supports = supports;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityExcavator), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Bucket.ToString(), Supports.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityExcavator? CreateEntityExcavator(string[] strs)
{
if (strs.Length != 7 || 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]));
}
}

View File

@ -45,5 +45,28 @@ public class EntityTrackedVehicle
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityTrackedVehicle), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTrackedVehicle? CreateEntityTrackedVehicle(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityTrackedVehicle))
{
return null;
}
return new EntityTrackedVehicle(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();
groupBox1.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBox1
@ -59,9 +66,9 @@
groupBox1.Controls.Add(panelStorage);
groupBox1.Controls.Add(comboBoxSelectorCompany);
groupBox1.Dock = DockStyle.Right;
groupBox1.Location = new Point(939, 0);
groupBox1.Location = new Point(939, 28);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(221, 806);
groupBox1.Size = new Size(221, 778);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Инструменты";
@ -75,9 +82,9 @@
panelCompanyTools.Controls.Add(buttonDelExcavator);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 473);
panelCompanyTools.Location = new Point(3, 476);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(215, 330);
panelCompanyTools.Size = new Size(215, 299);
panelCompanyTools.TabIndex = 9;
//
// buttonAddTrackedVehicle
@ -94,7 +101,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(18, 273);
buttonRefresh.Location = new Point(18, 221);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(176, 45);
buttonRefresh.TabIndex = 6;
@ -105,7 +112,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(18, 222);
buttonGoToCheck.Location = new Point(18, 170);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(171, 45);
buttonGoToCheck.TabIndex = 5;
@ -115,7 +122,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(13, 125);
maskedTextBox.Location = new Point(10, 75);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(191, 27);
@ -125,7 +132,7 @@
// buttonDelExcavator
//
buttonDelExcavator.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelExcavator.Location = new Point(18, 171);
buttonDelExcavator.Location = new Point(18, 119);
buttonDelExcavator.Name = "buttonDelExcavator";
buttonDelExcavator.Size = new Size(171, 45);
buttonDelExcavator.TabIndex = 4;
@ -239,12 +246,54 @@
// pictureBox
//
pictureBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
pictureBox.Location = new Point(1, 0);
pictureBox.Location = new Point(1, 27);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(938, 800);
pictureBox.Size = new Size(938, 773);
pictureBox.TabIndex = 1;
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(1160, 28);
menuStrip.TabIndex = 2;
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.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// FormTrackedVehicleCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -252,6 +301,8 @@
ClientSize = new Size(1160, 806);
Controls.Add(pictureBox);
Controls.Add(groupBox1);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormTrackedVehicleCollection";
Text = "Коллекция экскаваторов";
groupBox1.ResumeLayout(false);
@ -260,7 +311,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -283,5 +337,11 @@
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private PictureBox pictureBox;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -45,7 +45,7 @@ public partial class FormTrackedVehicleCollection : Form
private void ButtonAddCar_Click(object sender, EventArgs e)
{
FormTrackedVehicleConfig form = new();
form.Show();
form.AddEvent(SetCar);
}
@ -61,7 +61,7 @@ public partial class FormTrackedVehicleCollection : Form
return;
}
if (_company + car != -1)
if (_company + car != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
@ -244,5 +244,49 @@ public partial class FormTrackedVehicleCollection : 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)
{
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>