Compare commits

...

2 Commits

14 changed files with 438 additions and 12 deletions

View File

@ -48,7 +48,7 @@ namespace ProjectLiner.CollectionGenericObjects
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.SetMaxCount = GetMaxCount; _collection.MaxCount = GetMaxCount;
} }
/// <summary> /// <summary>

View File

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

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

View File

@ -15,8 +15,13 @@ namespace ProjectLiner.CollectionGenericObjects
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)
@ -33,6 +38,8 @@ namespace ProjectLiner.CollectionGenericObjects
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -105,5 +112,13 @@ namespace ProjectLiner.CollectionGenericObjects
_collection[position] = null; _collection[position] = null;
return temp; return temp;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
} }
} }

View File

@ -1,26 +1,45 @@
using ProjectLiner.CollectionGenericObjects; using ProjectLiner.CollectionGenericObjects;
using ProjectLiner.Drawnings;
/// <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 : DrawningCommonLiner
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); 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>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<string, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
/// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
@ -65,4 +84,125 @@ public class StorageCollection<T>
return _storages[name]; 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 FileStream fs = new(filename, FileMode.Create);
using StreamWriter sw = new StreamWriter(fs);
sw.Write(_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 (FileStream fs = new(filename, FileMode.Open))
{
using StreamReader sr = new StreamReader(fs);
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.Equals(_collectionKey))
{
return false;
}
_storages.Clear();
while (!sr.EndOfStream)
{
string[] record = sr.ReadLine().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?.CreateDrawningCommonLiner() is T commonLiner)
{
if (collection.Insert(commonLiner) == -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

@ -98,6 +98,17 @@ public class DrawningCommonLiner
_drawningLinerWidth = drawningLinerWight; _drawningLinerWidth = drawningLinerWight;
} }
/// <summary>
/// Конструктор для метода создания объекта из строки (ExtentionDrawningCommonLiner)
/// </summary>
/// <param name="CommonLiner"></param>
public DrawningCommonLiner(EntityCommonLiner? CommonLiner) : this()
{
EntityCommonLiner = CommonLiner;
}
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
/// </summary> /// </summary>

View File

@ -23,6 +23,16 @@ public class DrawningLiner : DrawningCommonLiner
} }
/// <summary>
/// Конструктор для метода создания объекта из строки (ExtentionDrawningAirplane)
/// </summary>
/// <param name="airplane"></param>
public DrawningLiner(EntityCommonLiner? liner) : base(liner)
{
if (liner != null)
EntityCommonLiner = liner;
}
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {
if (EntityCommonLiner == null || EntityCommonLiner is not EntityLiner liner || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityCommonLiner == null || EntityCommonLiner is not EntityLiner liner || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@ -0,0 +1,53 @@
using ProjectLiner.Entities;
namespace ProjectLiner.Drawnings;
public static class ExtentionDrawningLiner
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningCommonLiner? CreateDrawningCommonLiner(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityCommonLiner? CommonLiner = EntityLiner.CreateEntityLiner(strs);
if (CommonLiner != null)
{
return new DrawningLiner(CommonLiner);
}
CommonLiner = EntityCommonLiner.CreateEntityCommonLiner(strs);
if (CommonLiner != null)
{
return new DrawningCommonLiner(CommonLiner);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCommonLiner">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningCommonLiner drawningCommonLiner)
{
string[]? array = drawningCommonLiner?.EntityCommonLiner?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

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

View File

@ -1,4 +1,6 @@
namespace ProjectLiner.Entities; using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace ProjectLiner.Entities;
/// <summary> /// <summary>
/// Класс-сущность "Лайнер" /// Класс-сущность "Лайнер"
@ -51,4 +53,29 @@ public class EntityLiner: EntityCommonLiner
{ {
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
} }
/// <summary>
/// Переопределение метода создания объекта из массива строк
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityLiner), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Anchor.ToString(), Boats.ToString(), Pipe.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityLiner? CreateEntityLiner(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityLiner))
return null;
return new EntityLiner(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

@ -46,10 +46,17 @@
button5 = new Button(); button5 = new Button();
button3 = new Button(); button3 = new Button();
button4 = new Button(); button4 = new Button();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@ -58,9 +65,9 @@
groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(1052, 0); groupBoxTools.Location = new Point(1052, 49);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(272, 1063); groupBoxTools.Size = new Size(272, 1014);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
@ -183,9 +190,9 @@
// //
pictureBox.Dock = DockStyle.Bottom; pictureBox.Dock = DockStyle.Bottom;
pictureBox.Enabled = false; pictureBox.Enabled = false;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 51);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1052, 1063); pictureBox.Size = new Size(1052, 1012);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -197,10 +204,10 @@
panelCompanyTools.Controls.Add(button5); panelCompanyTools.Controls.Add(button5);
panelCompanyTools.Controls.Add(button3); panelCompanyTools.Controls.Add(button3);
panelCompanyTools.Controls.Add(button4); panelCompanyTools.Controls.Add(button4);
panelCompanyTools.Location = new Point(1052, 567); panelCompanyTools.Location = new Point(1052, 592);
panelCompanyTools.Margin = new Padding(5); panelCompanyTools.Margin = new Padding(5);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(272, 495); panelCompanyTools.Size = new Size(272, 470);
panelCompanyTools.TabIndex = 9; panelCompanyTools.TabIndex = 9;
// //
// buttonAddLiner // buttonAddLiner
@ -255,6 +262,48 @@
button4.UseVisualStyleBackColor = true; button4.UseVisualStyleBackColor = true;
button4.Click += ButtonGoToCheck_Click; button4.Click += ButtonGoToCheck_Click;
// //
// menuStrip
//
menuStrip.ImageScalingSize = new Size(26, 26);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1324, 49);
menuStrip.TabIndex = 10;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(104, 45);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(399, 50);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(399, 50);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormLinerCollection // FormLinerCollection
// //
AutoScaleDimensions = new SizeF(17F, 41F); AutoScaleDimensions = new SizeF(17F, 41F);
@ -263,6 +312,8 @@
Controls.Add(panelCompanyTools); Controls.Add(panelCompanyTools);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormLinerCollection"; Name = "FormLinerCollection";
Text = "Коллекция автомобилей"; Text = "Коллекция автомобилей";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
@ -271,7 +322,10 @@
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
panelCompanyTools.ResumeLayout(false); panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout(); panelCompanyTools.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@ -298,5 +352,11 @@
private Button button3; private Button button3;
private Button button4; private Button button4;
private Button buttonAddLiner; private Button buttonAddLiner;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
} }
} }

View File

@ -1,6 +1,7 @@
 
using ProjectLiner.CollectionGenericObjects; using ProjectLiner.CollectionGenericObjects;
using ProjectLiner.Drawnings; using ProjectLiner.Drawnings;
using System.Windows.Forms;
namespace ProjectLiner; namespace ProjectLiner;
/// <summary> /// <summary>
@ -222,4 +223,45 @@ public partial class FormLinerCollection : 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="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>228, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>519, 17</value>
</metadata>
</root> </root>

View File

@ -1,6 +1,7 @@
 
using ProjectLiner.Drawnings; using ProjectLiner.Drawnings;
using ProjectLiner.Entities; using ProjectLiner.Entities;
using static System.Runtime.InteropServices.JavaScript.JSType;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar; using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace ProjectLiner; namespace ProjectLiner;