Лабораторная работа №6

This commit is contained in:
Мария Котова 2024-04-21 17:15:02 +04:00
parent 340e44fdb1
commit b676330c29
14 changed files with 460 additions and 43 deletions

View File

@ -45,7 +45,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,14 @@ 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 WinFormsAppExcavator.CollectionGenericObjects;

namespace WinFormsAppExcavator.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
@ -12,7 +13,23 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// </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>
@ -53,4 +70,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i=0; i<Count; i++)
{
yield return _collection[i];
}
}
}

View File

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

namespace WinFormsAppExcavator.CollectionGenericObjects;
/// <summary>
/// параметризованный набор объектов
/// </summary>
@ -12,8 +13,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{ get
{
return _collection.Length;
}
set
{
if (value > 0)
@ -30,6 +35,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@ -110,4 +117,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[position] = null;
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i=0; i<_collection.Length;i++)
{
yield return _collection[i];
}
}
}

View File

@ -1,10 +1,13 @@
namespace WinFormsAppExcavator.CollectionGenericObjects;
using System.Text;
using WinFormsAppExcavator.Drawings;
namespace WinFormsAppExcavator.CollectionGenericObjects;
/// <summary>
/// класс-хранилище
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawingExcavatorEmpty
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -61,7 +64,148 @@ public class StorageCollection<T>
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name))
return _storages[name];
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 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)
{
//по идее этого произойти не должно
//if (strs == null)
//{
// return false;
//}
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?.CreateDrawningExcavatorEmpty() is T ship)
{
if (collection.Insert(ship) == -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

@ -7,6 +7,8 @@ namespace WinFormsAppExcavator.Drawings;
/// </summary>
public class DrawingExcavator : DrawingExcavatorEmpty
{
/// <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)
{
if (EntityExcavatorEmpty == null || EntityExcavatorEmpty is not EntityExcavator entityExcavator || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@ -1,15 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinFormsAppExcavator.Entity;
using WinFormsAppExcavator.Entity;
namespace WinFormsAppExcavator.Drawings;
public class DrawingExcavatorEmpty
{
/// <summary>
/// Класс-сущность
/// </summary>
@ -35,6 +29,8 @@ public class DrawingExcavatorEmpty
/// </summary>
protected int? _startPosY;
/// <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>

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;
}
/// <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;
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

@ -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(722, 0);
groupBoxTools.Location = new Point(722, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(220, 555);
groupBoxTools.Size = new Size(220, 527);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -75,14 +82,14 @@
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 324);
panelCompanyTools.Location = new Point(3, 327);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(214, 228);
panelCompanyTools.Size = new Size(214, 197);
panelCompanyTools.TabIndex = 9;
//
// maskedTextBox
//
maskedTextBox.Location = new Point(3, 96);
maskedTextBox.Location = new Point(0, 62);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(208, 27);
@ -92,7 +99,7 @@
// buttonAddExcavatorEmpty
//
buttonAddExcavatorEmpty.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddExcavatorEmpty.Location = new Point(5, 0);
buttonAddExcavatorEmpty.Location = new Point(3, 3);
buttonAddExcavatorEmpty.Name = "buttonAddExcavatorEmpty";
buttonAddExcavatorEmpty.Size = new Size(209, 53);
buttonAddExcavatorEmpty.TabIndex = 1;
@ -103,7 +110,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(5, 163);
buttonGoToCheck.Location = new Point(3, 131);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(206, 29);
buttonGoToCheck.TabIndex = 5;
@ -114,7 +121,7 @@
// buttonRemoveExcavator
//
buttonRemoveExcavator.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveExcavator.Location = new Point(5, 127);
buttonRemoveExcavator.Location = new Point(5, 95);
buttonRemoveExcavator.Name = "buttonRemoveExcavator";
buttonRemoveExcavator.Size = new Size(206, 30);
buttonRemoveExcavator.TabIndex = 4;
@ -125,7 +132,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(5, 198);
buttonRefresh.Location = new Point(3, 166);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(206, 27);
buttonRefresh.TabIndex = 6;
@ -239,12 +246,53 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(722, 555);
pictureBox.Size = new Size(722, 527);
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(942, 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
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -252,6 +300,8 @@
ClientSize = new Size(942, 555);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormExcavatorCollection";
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 Button buttonCollectionDel;
private ListBox listBoxCollection;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -1,4 +1,5 @@
using WinFormsAppExcavator.CollectionGenericObjects;
using System.Windows.Forms;
using WinFormsAppExcavator.CollectionGenericObjects;
using WinFormsAppExcavator.Drawings;
namespace WinFormsAppExcavator;
@ -40,7 +41,7 @@ public partial class FormExcavatorCollection : Form
/// <param name="e"></param>
private void ButtonAddExcavatorEmpty_Click(object sender, EventArgs e)
{
FormExcavatorConfig form= new ();
FormExcavatorConfig form = new();
// TODO передать метод
form.Show();
@ -237,5 +238,50 @@ public partial class FormExcavatorCollection : 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,16 @@
<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>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>61</value>
</metadata>
</root>

View File

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