5 Commits

13 changed files with 422 additions and 21 deletions

View File

@@ -41,7 +41,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.SetMaxCount = GetMaxCount; _collection.MaxCount = GetMaxCount;
} }
/// <summary> /// <summary>
/// Перегрузка оператора сложения для класса /// Перегрузка оператора сложения для класса

View File

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

View File

@@ -15,7 +15,11 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count; public int Count => _collection.Count;
public int SetMaxCount { public int MaxCount {
get
{
return _collection.Count;
}
set set
{ {
if (value > 0) if (value > 0)
@@ -24,6 +28,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
} }
public CollectionType GetCollectionType => CollectionType.List;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -59,4 +65,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position); _collection.RemoveAt(position);
return temp; return temp;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
} }

View File

@@ -11,8 +11,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
/// </summary> /// </summary>
private T?[] _collection; private T?[] _collection;
public int Count => _collection.Length; public int Count => _collection.Length;
public int SetMaxCount public int MaxCount
{ {
get
{
return _collection.Length;
}
set set
{ {
if (value > 0) if (value > 0)
@@ -28,6 +32,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -89,4 +95,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[position] = null; _collection[position] = null;
return myObject; return myObject;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
} }

View File

@@ -1,17 +1,36 @@
namespace ProjectCleaningCar.CollectionGenericObjects; using ProjectCleaningCar.Drawning;
using ProjectCleaningCar.Entities;
using System.Text;
namespace ProjectCleaningCar.CollectionGenericObjects;
/// <summary> /// <summary>
/// Класс-хранилище коллекций /// Класс-хранилище коллекций
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public class StorageCollection<T> public class StorageCollection<T>
where T : class where T : DrawningTruck
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
@@ -71,4 +90,124 @@ public class StorageCollection<T>
return null; return null;
} }
} }
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new(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 = 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?.CreateDrawningCar() is T truck)
{
if (collection.Insert(truck) == -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,17 @@ public class DrawningCleaningCar : DrawningTruck
{ {
EntityTruck = new EntityCleaningCar(speed, weight, bodyColor, additionalColor, tank, sweepingBrush, flashlight); EntityTruck = new EntityCleaningCar(speed, weight, bodyColor, additionalColor, tank, sweepingBrush, flashlight);
} }
/// <summary>
/// Конструктор для Extention
/// </summary>
/// <param name="cleaningCar"></param>
public DrawningCleaningCar(EntityCleaningCar cleaningCar) : base(132, 65)
{
if (cleaningCar == null) return;
EntityTruck = new EntityCleaningCar(cleaningCar.Speed,cleaningCar.Weight, cleaningCar.BodyColor,
cleaningCar.AdditionalColor, cleaningCar.Tank, cleaningCar.SweepingBrush, cleaningCar.Flashlight);
}
/// <summary> /// <summary>
/// Отрисовка объекта /// Отрисовка объекта
/// </summary> /// </summary>

View File

@@ -81,6 +81,15 @@ public class DrawningTruck
_drawningTruckHeight = drawningTruckHeight; _drawningTruckHeight = drawningTruckHeight;
} }
/// <summary> /// <summary>
/// Новый конструктор
/// </summary>
/// <param name="truck"></param>
public DrawningTruck(EntityTruck? truck) : this()
{
if (truck == null) return;
EntityTruck = new EntityTruck(truck.Speed, truck.Weight, truck.BodyColor);
}
/// <summary>
/// Установка границ поля /// Установка границ поля
/// </summary> /// </summary>
/// <param name="width">Ширина поля</param> /// <param name="width">Ширина поля</param>

View File

@@ -0,0 +1,46 @@
using ProjectCleaningCar.Entities;
namespace ProjectCleaningCar.Drawning;
/// <summary>
/// Расширение для класса EntityTruck
/// </summary>
public static class ExtentionDrawningTruck
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
public static DrawningTruck? CreateDrawningCar(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTruck? truck = EntityCleaningCar.CreateEntityCleaningCar(strs);
if (truck != null)
{
return new DrawningCleaningCar((EntityCleaningCar)truck);
}
truck = EntityTruck.CreateEntityCar(strs);
if (truck != null)
{
return new DrawningTruck(truck);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningTruck drawningTruck)
{
string[]? array = drawningTruck?.EntityTruck?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -41,4 +41,28 @@ public class EntityCleaningCar : EntityTruck
SweepingBrush = sweepingBrush; SweepingBrush = sweepingBrush;
Flashlight = flashlight; Flashlight = flashlight;
} }
/// <summary>
/// Получение строк со значениями свойств продвинутого объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityCleaningCar), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,
Tank.ToString(), SweepingBrush.ToString(), Flashlight.ToString()};
}
/// <summary>
/// Создание продвинутого объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityCleaningCar? CreateEntityCleaningCar(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityCleaningCar))
{
return null;
}
return new EntityCleaningCar(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

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

View File

@@ -46,10 +46,17 @@
labelCollectionName = new Label(); labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
menuStrip = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
tools.SuspendLayout(); tools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// tools // tools
@@ -59,9 +66,9 @@
tools.Controls.Add(panelStorage); tools.Controls.Add(panelStorage);
tools.Controls.Add(comboBoxSelectorCompany); tools.Controls.Add(comboBoxSelectorCompany);
tools.Dock = DockStyle.Right; tools.Dock = DockStyle.Right;
tools.Location = new Point(783, 0); tools.Location = new Point(783, 24);
tools.Name = "tools"; tools.Name = "tools";
tools.Size = new Size(208, 606); tools.Size = new Size(208, 582);
tools.TabIndex = 0; tools.TabIndex = 0;
tools.TabStop = false; tools.TabStop = false;
tools.Text = "Инструменты"; tools.Text = "Инструменты";
@@ -77,12 +84,12 @@
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 354); panelCompanyTools.Location = new Point(3, 354);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(202, 249); panelCompanyTools.Size = new Size(202, 225);
panelCompanyTools.TabIndex = 7; panelCompanyTools.TabIndex = 7;
// //
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Location = new Point(3, 208); buttonRefresh.Location = new Point(3, 178);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(196, 38); buttonRefresh.Size = new Size(196, 38);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
@@ -92,7 +99,7 @@
// //
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Location = new Point(3, 164); buttonGoToCheck.Location = new Point(3, 134);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(196, 38); buttonGoToCheck.Size = new Size(196, 38);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
@@ -113,7 +120,7 @@
// //
// maskedTextBoxPosition // maskedTextBoxPosition
// //
maskedTextBoxPosition.Location = new Point(3, 91); maskedTextBoxPosition.Location = new Point(3, 61);
maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(196, 23); maskedTextBoxPosition.Size = new Size(196, 23);
@@ -122,7 +129,7 @@
// //
// buttonDelCar // buttonDelCar
// //
buttonDelCar.Location = new Point(3, 120); buttonDelCar.Location = new Point(3, 90);
buttonDelCar.Name = "buttonDelCar"; buttonDelCar.Name = "buttonDelCar";
buttonDelCar.Size = new Size(196, 38); buttonDelCar.Size = new Size(196, 38);
buttonDelCar.TabIndex = 4; buttonDelCar.TabIndex = 4;
@@ -237,12 +244,52 @@
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(783, 606); pictureBox.Size = new Size(783, 582);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(991, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// fileToolStripMenuItem
//
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(48, 20);
fileToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormCleaningCarCollection // FormCleaningCarCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@@ -250,6 +297,8 @@
ClientSize = new Size(991, 606); ClientSize = new Size(991, 606);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(tools); Controls.Add(tools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormCleaningCarCollection"; Name = "FormCleaningCarCollection";
Text = "Коллекция уборочных машин"; Text = "Коллекция уборочных машин";
tools.ResumeLayout(false); tools.ResumeLayout(false);
@@ -258,7 +307,10 @@
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@@ -281,5 +333,11 @@
private TextBox textBoxCollectionName; private TextBox textBoxCollectionName;
private Button buttonCreateCompany; private Button buttonCreateCompany;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
} }
} }

View File

@@ -235,4 +235,47 @@ public partial class FormCleaningCarCollection : Form
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RerfreshListBoxItems(); 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"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </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>126, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
</root> </root>