Готовая Lab_6

This commit is contained in:
Максим Егоров 2024-05-05 18:52:43 +03:00
parent 688a6b5333
commit e0a52ea60c
4 changed files with 225 additions and 2 deletions

View File

@ -37,6 +37,8 @@ namespace Sailboat.Generics
/// Набор объектов /// Набор объектов
/// </summary> /// </summary>
private readonly SetGeneric<T> _collection; private readonly SetGeneric<T> _collection;
internal IEnumerable<DrawingBoat> GetBoats;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>

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($"BoatStorage{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,63 @@
using Sailboat.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
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

@ -165,6 +165,54 @@
buttonAddBoat.UseVisualStyleBackColor = true; buttonAddBoat.UseVisualStyleBackColor = true;
buttonAddBoat.Click += buttonAddBoat_Click; buttonAddBoat.Click += buttonAddBoat_Click;
// //
// menuStrip
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem1,
this.ToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(209, 28);
this.menuStrip.TabIndex = 5;
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(14, 24);
//
// ToolStripMenuItem
//
this.ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.ToolStripMenuItem.Name = "ToolStripMenuItem";
this.ToolStripMenuItem.Size = new System.Drawing.Size(59, 24);
this.ToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog";
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormBoatCollection // FormBoatCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@ -197,5 +245,14 @@
private ListBox listBoxStorages; private ListBox listBoxStorages;
private Button buttonAddObject; private Button buttonAddObject;
private TextBox textBoxStorageName; private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem toolStripMenuItem1;
private ToolStripMenuItem ToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private EventHandler SaveToolStripMenuItem_Click;
private EventHandler LoadToolStripMenuItem_Click;
} }
} }