лабораторная работа 6

This commit is contained in:
Anya 2024-05-24 01:18:13 +04:00
parent 11aabfe96d
commit 3655b5bd9a
11 changed files with 320 additions and 28 deletions

View File

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

View File

@ -21,7 +21,7 @@ namespace ProjectBus.CollectionGenericObject;
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию

View File

@ -21,10 +21,21 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public CollectionType GetCollectionType => CollectionType.List;
public int MaxCount
{
get { return Count; }
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
/// <summary>
/// Конструктор
/// </summary>

View File

@ -21,8 +21,12 @@ namespace ProjectBus.CollectionGenericObject;
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@ -37,6 +41,7 @@ namespace ProjectBus.CollectionGenericObject;
}
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;

View File

@ -1,4 +1,5 @@
using System;
using ProjectBus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -12,7 +13,7 @@ namespace ProjectBus.CollectionGenericObject;
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningSimpleBus
{/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
@ -23,6 +24,21 @@ public 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>
@ -77,4 +93,137 @@ public class StorageCollection<T>
return _storages[name];
}
}
/// <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);
// не сохраняем пустые коллекции
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?.CreateDrawningSimpleBus() is T bus)
{
if (collection.Insert(bus) == -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

@ -20,6 +20,14 @@ public class EntitySimpleBus
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
/// <param name="color"></param>
public void SetBodyColor(Color color)
{
BodyColor = color;
}
/// <summary>

View File

@ -46,10 +46,17 @@
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
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
@ -57,9 +64,9 @@
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(1018, 0);
groupBoxTools.Location = new Point(1018, 40);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(356, 1058);
groupBoxTools.Size = new Size(356, 1018);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -73,14 +80,14 @@
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 543);
panelCompanyTools.Location = new Point(3, 570);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(350, 512);
panelCompanyTools.Size = new Size(350, 445);
panelCompanyTools.TabIndex = 8;
//
// buttonAddSimpleBus
//
buttonAddSimpleBus.Location = new Point(9, 3);
buttonAddSimpleBus.Location = new Point(9, 48);
buttonAddSimpleBus.Name = "buttonAddSimpleBus";
buttonAddSimpleBus.Size = new Size(318, 59);
buttonAddSimpleBus.TabIndex = 1;
@ -90,7 +97,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(15, 173);
maskedTextBox.Location = new Point(13, 135);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(306, 39);
@ -100,7 +107,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(6, 366);
buttonRefresh.Location = new Point(6, 365);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(328, 49);
buttonRefresh.TabIndex = 7;
@ -111,7 +118,7 @@
// buttonDelBus
//
buttonDelBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelBus.Location = new Point(6, 231);
buttonDelBus.Location = new Point(6, 200);
buttonDelBus.Name = "buttonDelBus";
buttonDelBus.Size = new Size(321, 46);
buttonDelBus.TabIndex = 5;
@ -122,7 +129,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(6, 293);
buttonGoToCheck.Location = new Point(6, 277);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(328, 58);
buttonGoToCheck.TabIndex = 6;
@ -238,12 +245,53 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 40);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1018, 1058);
pictureBox.Size = new Size(1018, 1018);
pictureBox.TabIndex = 0;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(32, 32);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1374, 40);
menuStrip.TabIndex = 1;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(90, 36);
файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
SaveToolStripMenuItem.Size = new Size(361, 44);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
LoadToolStripMenuItem.Size = new Size(361, 44);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormSimpleBusCollection
//
AutoScaleDimensions = new SizeF(13F, 32F);
@ -251,6 +299,8 @@
ClientSize = new Size(1374, 1058);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormSimpleBusCollection";
Text = "Коллекция автобусов";
groupBoxTools.ResumeLayout(false);
@ -259,7 +309,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
@ -285,5 +338,11 @@
private Button buttonCollectionAdd;
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

@ -1,6 +1,7 @@
using ProjectBus.MovementStrategy;
using ProjectBus.Drawnings;
using ProjectBus.CollectionGenericObject;
using System.Windows.Forms;
namespace ProjectBus;
@ -294,6 +295,48 @@ public partial class FormSimpleBusCollection : Form
panelCompanyTools.Enabled = true;
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>204, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>447, 17</value>
</metadata>
</root>

View File

@ -74,7 +74,7 @@
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(975, 431);
groupBoxConfig.Size = new Size(975, 829);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
@ -161,6 +161,8 @@
//
// panelRed
//
panelRed.AllowDrop = true;
panelRed.AutoSize = true;
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(21, 38);
panelRed.Name = "panelRed";
@ -252,7 +254,7 @@
//
pictureBoxObject.Location = new Point(18, 100);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(379, 168);
pictureBoxObject.Size = new Size(585, 593);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
@ -283,13 +285,14 @@
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(1035, 12);
panelObject.Name = "panelObject";
panelObject.Size = new Size(412, 287);
panelObject.Size = new Size(441, 315);
panelObject.TabIndex = 4;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(226, 23);
labelAdditionalColor.Name = "labelAdditionalColor";
@ -302,10 +305,11 @@
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(18, 23);
labelBodyColor.Location = new Point(38, 23);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(171, 57);
labelBodyColor.Size = new Size(140, 57);
labelBodyColor.TabIndex = 9;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
@ -316,7 +320,7 @@
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1488, 431);
ClientSize = new Size(1745, 829);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
@ -326,6 +330,7 @@
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColors.ResumeLayout(false);
groupBoxColors.PerformLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();

View File

@ -146,8 +146,11 @@ public partial class FormSimpleBusConfig : Form
{
if (_simpleBus != null)
{
_simpleBus.EntitySimpleBus.setBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
if (_simpleBus != null)
{
_simpleBus.EntitySimpleBus.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}
}
}
@ -180,12 +183,12 @@ public partial class FormSimpleBusConfig : Form
/// <param name="e"></param>
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_simpleBus is DrawningBus bus)
if (_simpleBus.EntitySimpleBus is EntityBus _bus)
{
labelAdditionalColor.BackColor = (Color)e.Data.GetData(typeof(Color));
bus.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
_bus.setAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
DrawObject();
}
private void ButtonAdd_Click(object sender, EventArgs e)