Compare commits

...

8 Commits

6 changed files with 273 additions and 4 deletions

View File

@ -38,6 +38,10 @@ namespace Sailboat.Generics
/// </summary> /// </summary>
private readonly SetGeneric<T> _collection; private readonly SetGeneric<T> _collection;
/// <summary> /// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetBoats => _collection.GetBoats();
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="picWidth"></param> /// <param name="picWidth"></param>

View File

@ -28,6 +28,18 @@ namespace Sailboat.Generics
/// </summary> /// </summary>
private readonly int _pictureHeight; private readonly int _pictureHeight;
/// <summary> /// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="pictureWidth"></param> /// <param name="pictureWidth"></param>
@ -80,5 +92,94 @@ namespace Sailboat.Generics
return null; return null;
} }
} }
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> record in _boatStorages)
{
StringBuilder records = new();
foreach (DrawingBoat? elem in record.Value.GetBoats)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write($"PlaneStorage{Environment.NewLine}{data}");
}
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("BoatStorage"))
{
return false;
}
_boatStorages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
if (strs == null)
{
return false;
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingBoat? boat = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight);
if (boat != null)
{
if (!(collection + boat))
{
return false;
}
}
}
_boatStorages.Add(record[0], collection);
}
return true;
}
}
} }
} }

View File

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sailboat.Entities;
namespace Sailboat.DrawingObjects
{
public static class ExtentionDrawingBoat
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingBoat? CreateDrawingBoat(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingBoat(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawingSailboat(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]),
width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingBoat drawingBoat, char separatorForObject)
{
var boat = drawingBoat.EntityBoat;
if (boat == null)
{
return string.Empty;
}
var str = $"{boat.Speed}{separatorForObject}{boat.Weight}{separatorForObject}{boat.BodyColor.Name}";
if (boat is not EntitySailboat sailboat)
{
return str;
}
return $"{str}{separatorForObject}{sailboat.AdditionalColor.Name}{separatorForObject}{sailboat.Hull}{separatorForObject}{sailboat.Sail}";
}
}
}

View File

@ -39,9 +39,16 @@
listBoxStorages = new ListBox(); listBoxStorages = new ListBox();
buttonDelObject = new Button(); buttonDelObject = new Button();
buttonAddObject = new Button(); buttonAddObject = new Button();
menuStrip = new MenuStrip();
ToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
groupBoxCollection.SuspendLayout(); groupBoxCollection.SuspendLayout();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// pictureBoxCollection // pictureBoxCollection
@ -55,7 +62,7 @@
// //
// buttonAddBoat // buttonAddBoat
// //
buttonAddBoat.Location = new Point(5, 345); buttonAddBoat.Location = new Point(5, 402);
buttonAddBoat.Name = "buttonAddBoat"; buttonAddBoat.Name = "buttonAddBoat";
buttonAddBoat.Size = new Size(197, 45); buttonAddBoat.Size = new Size(197, 45);
buttonAddBoat.TabIndex = 1; buttonAddBoat.TabIndex = 1;
@ -65,7 +72,7 @@
// //
// buttonRemoveBoat // buttonRemoveBoat
// //
buttonRemoveBoat.Location = new Point(5, 462); buttonRemoveBoat.Location = new Point(5, 486);
buttonRemoveBoat.Name = "buttonRemoveBoat"; buttonRemoveBoat.Name = "buttonRemoveBoat";
buttonRemoveBoat.Size = new Size(197, 45); buttonRemoveBoat.Size = new Size(197, 45);
buttonRemoveBoat.TabIndex = 2; buttonRemoveBoat.TabIndex = 2;
@ -85,7 +92,7 @@
// //
// maskedTextBoxNumber // maskedTextBoxNumber
// //
maskedTextBoxNumber.Location = new Point(39, 429); maskedTextBoxNumber.Location = new Point(39, 453);
maskedTextBoxNumber.Name = "maskedTextBoxNumber"; maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(138, 27); maskedTextBoxNumber.Size = new Size(138, 27);
maskedTextBoxNumber.TabIndex = 4; maskedTextBoxNumber.TabIndex = 4;
@ -97,6 +104,7 @@
groupBoxTools.Controls.Add(buttonRefreshCollection); groupBoxTools.Controls.Add(buttonRefreshCollection);
groupBoxTools.Controls.Add(maskedTextBoxNumber); groupBoxTools.Controls.Add(maskedTextBoxNumber);
groupBoxTools.Controls.Add(buttonRemoveBoat); groupBoxTools.Controls.Add(buttonRemoveBoat);
groupBoxTools.Controls.Add(menuStrip);
groupBoxTools.Location = new Point(756, 12); groupBoxTools.Location = new Point(756, 12);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(209, 588); groupBoxTools.Size = new Size(209, 588);
@ -110,7 +118,7 @@
groupBoxCollection.Controls.Add(listBoxStorages); groupBoxCollection.Controls.Add(listBoxStorages);
groupBoxCollection.Controls.Add(buttonDelObject); groupBoxCollection.Controls.Add(buttonDelObject);
groupBoxCollection.Controls.Add(buttonAddObject); groupBoxCollection.Controls.Add(buttonAddObject);
groupBoxCollection.Location = new Point(6, 26); groupBoxCollection.Location = new Point(6, 75);
groupBoxCollection.Name = "groupBoxCollection"; groupBoxCollection.Name = "groupBoxCollection";
groupBoxCollection.Size = new Size(196, 299); groupBoxCollection.Size = new Size(196, 299);
groupBoxCollection.TabIndex = 5; groupBoxCollection.TabIndex = 5;
@ -154,6 +162,46 @@
buttonAddObject.UseVisualStyleBackColor = true; buttonAddObject.UseVisualStyleBackColor = true;
buttonAddObject.Click += buttonAddObject_Click; buttonAddObject.Click += buttonAddObject_Click;
// //
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { ToolStripMenuItem });
menuStrip.Location = new Point(3, 23);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(203, 28);
menuStrip.TabIndex = 6;
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.Size = new Size(224, 26);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(224, 26);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormBoatCollection // FormBoatCollection
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
@ -168,6 +216,8 @@
groupBoxTools.PerformLayout(); groupBoxTools.PerformLayout();
groupBoxCollection.ResumeLayout(false); groupBoxCollection.ResumeLayout(false);
groupBoxCollection.PerformLayout(); groupBoxCollection.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();
} }
@ -185,5 +235,11 @@
private Button buttonDelObject; private Button buttonDelObject;
private Button buttonAddObject; private Button buttonAddObject;
private TextBox textBoxStorageName; private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem ToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
} }
} }

View File

@ -148,5 +148,40 @@ namespace Sailboat
ReloadObjects(); ReloadObjects();
} }
} }
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
ReloadObjects();
}
} }
} }

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>480, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>608, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>778, 17</value>
</metadata>
</root> </root>