PI-13 Kobin V.O. LabWork06 Simple #6

Closed
vkobi wants to merge 2 commits from LabWork06 into LabWork05
14 changed files with 444 additions and 21 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

@ -19,7 +19,21 @@ 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>
/// Конструктор
@ -79,4 +93,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -14,8 +14,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 +36,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@ -115,4 +121,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
// TODO удаление объекта из массива, присвоив элементу массива значение null
return tmp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -1,12 +1,30 @@
namespace WarmlyLocomotive.CollectionGenericObjects;
using System.Text;
using WarmlyLocomotive.Drawnings;
namespace WarmlyLocomotive.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningLocomotive
{
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
@ -80,4 +98,133 @@ public class StorageCollection<T>
}
}
/// <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);
}
//StringBuilder sb = new();
Review

Закомментированного кода быть не должно

Закомментированного кода быть не должно
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(_collectionKey);
//sb.Append(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
sw.Write(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sw.Write(value.Key);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.GetCollectionType);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.MaxCount);
sw.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sw.Write(data);
sw.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 = new(filename))
{
string line = reader.ReadLine();
if (line == null || line.Length == 0)
{
return false;
}
if (!line.Equals(_collectionKey))
{
return false;
}
_storages.Clear();
while ((line = reader.ReadLine()) != null)
{
string[] record = line.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?.CreateDrawningLocomotive() is T locomotive)
{
if (collection.Insert(locomotive) == -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

@ -76,6 +76,17 @@ public class DrawningLocomotive
EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor);
}
public DrawningLocomotive(EntityLocomotive? entityLocomotive) : this()
{
if(entityLocomotive == null)
{
return;
}
EntityLocomotive = new EntityLocomotive(entityLocomotive.Speed, entityLocomotive.Weight, entityLocomotive.BodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>

View File

@ -21,6 +21,15 @@ public class DrawningWarmlyLocomotive : DrawningLocomotive
EntityLocomotive = new EntityWarmlyLocomotive(speed, weight, bodyColor, additionalColor, chimney, compartment);
}
public DrawningWarmlyLocomotive(EntityWarmlyLocomotive entityWarmlyLocomotive) : base(130, 50)
{
if(entityWarmlyLocomotive == null)
{
return;
}
EntityLocomotive = new EntityWarmlyLocomotive(entityWarmlyLocomotive.Speed, entityWarmlyLocomotive.Weight, entityWarmlyLocomotive.BodyColor, entityWarmlyLocomotive.AdditionalColor, entityWarmlyLocomotive.Chimney, entityWarmlyLocomotive.Compartment);
}
public override void DrawTransport(Graphics g)
{
if (EntityLocomotive == null || EntityLocomotive is not EntityWarmlyLocomotive warmlyLocmotive || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@ -0,0 +1,50 @@
using WarmlyLocomotive.Entities;
namespace WarmlyLocomotive.Drawnings;
/// <summary>
/// Расширение для класса EntityLocomotive
/// </summary>
public static class ExtentionDrawningLocomotive
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningLocomotive? CreateDrawningLocomotive(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityLocomotive? locomotive = EntityWarmlyLocomotive.CreateEntityWarmlyLocomotive(strs);
if (locomotive != null)
{
return new DrawningWarmlyLocomotive((EntityWarmlyLocomotive)locomotive);
}
locomotive = EntityLocomotive.CreateEntityLocomotive(strs);
if (locomotive != null)
{
return new DrawningLocomotive(locomotive);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningLocomotive">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningLocomotive drawningLocomotive)
{
string[]? array = drawningLocomotive?.EntityLocomotive?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

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

View File

@ -40,4 +40,26 @@ public class EntityWarmlyLocomotive : EntityLocomotive
Chimney = chimney;
Compartment = compartment;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityWarmlyLocomotive), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Chimney.ToString(), Compartment.ToString()};
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityWarmlyLocomotive? CreateEntityWarmlyLocomotive(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityWarmlyLocomotive))
{
return null;
}
return new EntityWarmlyLocomotive(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

@ -46,10 +46,17 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
fileToolStripMenuItem = 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(821, 0);
groupBoxTools.Location = new Point(821, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(193, 618);
groupBoxTools.Size = new Size(193, 590);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -75,15 +82,15 @@
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 347);
panelCompanyTools.Location = new Point(3, 341);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(187, 268);
panelCompanyTools.Size = new Size(187, 246);
panelCompanyTools.TabIndex = 9;
//
// buttonAddLocomotive
//
buttonAddLocomotive.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddLocomotive.Location = new Point(6, 3);
buttonAddLocomotive.Location = new Point(3, 3);
buttonAddLocomotive.Name = "buttonAddLocomotive";
buttonAddLocomotive.Size = new Size(172, 48);
buttonAddLocomotive.TabIndex = 1;
@ -93,7 +100,7 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(6, 111);
maskedTextBoxPosition.Location = new Point(0, 57);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(175, 27);
@ -103,7 +110,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(6, 231);
buttonRefresh.Location = new Point(0, 200);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(172, 34);
buttonRefresh.TabIndex = 6;
@ -114,7 +121,7 @@
// buttonRemoveLocomotive
//
buttonRemoveLocomotive.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveLocomotive.Location = new Point(6, 144);
buttonRemoveLocomotive.Location = new Point(-3, 90);
buttonRemoveLocomotive.Name = "buttonRemoveLocomotive";
buttonRemoveLocomotive.Size = new Size(172, 48);
buttonRemoveLocomotive.TabIndex = 4;
@ -125,7 +132,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(6, 195);
buttonGoToCheck.Location = new Point(0, 144);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(172, 33);
buttonGoToCheck.TabIndex = 5;
@ -240,12 +247,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(821, 618);
pictureBox.Size = new Size(821, 590);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1014, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// fileToolStripMenuItem
//
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(59, 24);
fileToolStripMenuItem.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";
//
// FormLocomotiveCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -253,6 +301,8 @@
ClientSize = new Size(1014, 618);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormLocomotiveCollection";
Text = "Коллекция локомотивов";
groupBoxTools.ResumeLayout(false);
@ -261,7 +311,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -284,5 +337,11 @@
private ListBox listBoxCollection;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -44,6 +44,10 @@ public partial class FormLocomotiveCollection : Form
/// <param name="e"></param>
private void ButtonAddLocomotive_Click(object sender, EventArgs e)
{
if(_company == null)
{
return;
}
FormLocomotiveConfig form = new();
// TODO передать метод
form.AddEvent(SetLocomotive);
@ -237,4 +241,46 @@ public partial class FormLocomotiveCollection : Form
}
}
}
/// <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>81</value>
</metadata>
</root>

View File

@ -16,7 +16,7 @@ public partial class FormLocomotiveConfig : Form
/// <summary>
/// Событие для передачи объекта
/// </summary>
private event LocomotiveDelegate? LocomotiveDelegate;
private event Action<DrawningLocomotive>? LocomotiveDelegate;
/// <summary>
/// Конструктор
@ -34,15 +34,13 @@ public partial class FormLocomotiveConfig : Form
panelBlue.MouseDown += Panel_MouseDown;
buttonCancel.Click += (events, e) => Close();
}
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="locomotiveDelegate"></param>
public void AddEvent(LocomotiveDelegate locomotiveDelegate)
public void AddEvent(Action<DrawningLocomotive> locomotiveDelegate)
{
LocomotiveDelegate += locomotiveDelegate;
}