Второй этап Lab_8

This commit is contained in:
Максим Егоров 2024-10-06 19:22:41 +04:00
parent 01b12c835a
commit dcb622b7d5
7 changed files with 117 additions and 149 deletions

View File

@ -41,6 +41,8 @@ namespace Sailboat.Generics
/// Получение объектов коллекции /// Получение объектов коллекции
/// </summary> /// </summary>
public IEnumerable<T?> GetBoats => _collection.GetBoats(); public IEnumerable<T?> GetBoats => _collection.GetBoats();
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -60,13 +62,13 @@ namespace Sailboat.Generics
/// <param name="collect"></param> /// <param name="collect"></param>
/// <param name="obj"></param> /// <param name="obj"></param>
/// <returns></returns> /// <returns></returns>
public static bool operator +(BoatsGenericCollection<T, U> collect, T? obj) public static int operator +(BoatsGenericCollection<T, U> collect, T? obj)
{ {
if (obj == null) if (obj == null)
{ {
return false; return -1;
} }
return (bool)collect?._collection.Insert(obj); return collect._collection.Insert(obj, new DrawingBoatEqutables());
} }
/// <summary> /// <summary>
/// Перегрузка оператора вычитания /// Перегрузка оператора вычитания
@ -74,14 +76,11 @@ namespace Sailboat.Generics
/// <param name="collect"></param> /// <param name="collect"></param>
/// <param name="pos"></param> /// <param name="pos"></param>
/// <returns></returns> /// <returns></returns>
public static bool operator -(BoatsGenericCollection<T, U> collect, int pos) public static T? operator -(BoatsGenericCollection<T, U> collect, int pos)
{ {
T? obj = collect._collection[pos]; T? obj = collect._collection[pos];
if (obj != null)
{
}
collect._collection.Remove(pos); collect._collection.Remove(pos);
return false; return obj;
} }
/// <summary> /// <summary>

View File

@ -5,6 +5,7 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Sailboat.DrawingObjects; using Sailboat.DrawingObjects;
using Sailboat.MovementStrategy; using Sailboat.MovementStrategy;
using Sailboat.Exceptions;
namespace Sailboat.Generics namespace Sailboat.Generics
{ {
@ -13,11 +14,11 @@ namespace Sailboat.Generics
/// <summary> /// <summary>
/// Словарь (хранилище) /// Словарь (хранилище)
/// </summary> /// </summary>
readonly Dictionary<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> _boatStorages; readonly Dictionary<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> _boatStorages;
/// <summary> /// <summary>
/// Возвращение списка названий наборов /// Возвращение списка названий наборов
/// </summary> /// </summary>
public List<string> Keys => _boatStorages.Keys.ToList(); public List<BoatsCollectionInfo> Keys => _boatStorages.Keys.ToList();
/// <summary> /// <summary>
/// Ширина окна отрисовки /// Ширина окна отрисовки
/// </summary> /// </summary>
@ -45,8 +46,7 @@ namespace Sailboat.Generics
/// <param name="pictureHeight"></param> /// <param name="pictureHeight"></param>
public BoatsGenericStorage(int pictureWidth, int pictureHeight) public BoatsGenericStorage(int pictureWidth, int pictureHeight)
{ {
_boatStorages = new Dictionary<string, _boatStorages = new Dictionary<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
@ -56,11 +56,7 @@ namespace Sailboat.Generics
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void AddSet(string name) public void AddSet(string name)
{ {
if (_boatStorages.ContainsKey(name)) _boatStorages.Add(new BoatsCollectionInfo(name, string.Empty), new BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>(_pictureWidth, _pictureHeight));
{
return;
}
_boatStorages[name] = new BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>(_pictureWidth, _pictureHeight);
} }
/// <summary> /// <summary>
/// Удаление набора /// Удаление набора
@ -68,26 +64,22 @@ namespace Sailboat.Generics
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void DelSet(string name) public void DelSet(string name)
{ {
if (!_boatStorages.ContainsKey(name)) if (!_boatStorages.ContainsKey(new BoatsCollectionInfo(name, string.Empty)))
{
return; return;
} _boatStorages.Remove(new BoatsCollectionInfo(name, string.Empty));
_boatStorages.Remove(name);
} }
/// <summary> /// <summary>
/// Доступ к набору /// Доступ к набору
/// </summary> /// </summary>
/// <param name="ind"></param> /// <param name="ind"></param>
/// <returns></returns> /// <returns></returns>
public BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>? public BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>? this[string ind]
this[string ind]
{ {
get get
{ {
if (_boatStorages.ContainsKey(ind)) BoatsCollectionInfo indObj = new BoatsCollectionInfo(ind, string.Empty);
{ if (_boatStorages.ContainsKey(indObj))
return _boatStorages[ind]; return _boatStorages[indObj];
}
return null; return null;
} }
} }
@ -96,32 +88,36 @@ namespace Sailboat.Generics
/// Сохранение информации по лодкам в хранилище в файл /// Сохранение информации по лодкам в хранилище в файл
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
public bool SaveData(string filename) /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> record in _boatStorages) foreach (KeyValuePair<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> record in _boatStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
foreach (DrawingBoat? elem in record.Value.GetBoats) foreach (DrawingBoat? elem in record.Value.GetBoats)
{ {
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
} }
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
} }
if (data.Length == 0) if (data.Length == 0)
{ {
throw new Exception("Невалидная операция, нет данных для сохранения"); throw new InvalidOperationException("Файл не найден, невалидная операция, нет данных для сохранения");
} }
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
{ {
writer.Write($"SailboatStorage{Environment.NewLine}{data}"); writer.WriteLine("BoatStorage");
writer.Write(data.ToString());
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по лодкам в хранилище из файла /// Загрузка информации по лодкам в хранилище из файла
/// </summary> /// </summary>
@ -131,55 +127,43 @@ namespace Sailboat.Generics
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new Exception("Файл не найден"); throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader sr = new(filename))
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{ {
byte[] b = new byte[fs.Length]; string str = sr.ReadLine();
UTF8Encoding temp = new(true); if (str == null || str.Length == 0)
while (fs.Read(b, 0, b.Length) > 0)
{ {
bufferTextFromFile += temp.GetString(b); throw new NullReferenceException("Нет данных для загрузки");
} }
} if (!str.StartsWith("BoatStorage"))
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{ {
throw new Exception("Нет данных для загрузки"); throw new InvalidDataException("Неверный формат данных");
} }
if (!strs[0].StartsWith("BoatStorage"))
{
//если нет такой записи, то это не те данные
throw new Exception("Неверный формат данных");
}
_boatStorages.Clear(); _boatStorages.Clear();
foreach (string data in strs) while ((str = sr.ReadLine()) != null)
{ {
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2) if (record.Length != 2)
{ {
continue; continue;
} }
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat> collection = new(_pictureWidth, _pictureHeight); BoatsGenericCollection<DrawingBoat, DrawingObjectBoat> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set.Reverse())
{ {
DrawingBoat? boat = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight); DrawingBoat? truck = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight);
if (boat != null) if (truck != null)
{ {
if (!(collection + boat)) if (collection + truck == -1)
{ {
throw new Exception("Ошибка добавления в коллекцию"); throw new ApplicationException("Ошибка добавления в коллекцию");
} }
} }
} }
_boatStorages.Add(record[0], collection); _boatStorages.Add(new BoatsCollectionInfo(record[0], string.Empty), collection);
} }
}
} }
} }
} }

View File

@ -77,6 +77,7 @@ namespace Sailboat
panelTools.Name = "panelTools"; panelTools.Name = "panelTools";
panelTools.Size = new Size(183, 542); panelTools.Size = new Size(183, 542);
panelTools.TabIndex = 1; panelTools.TabIndex = 1;
this.panelTools.TabIndex = 1;
// //
// panelCollection // panelCollection
// //
@ -182,6 +183,7 @@ namespace Sailboat
menuStrip.Padding = new Padding(5, 2, 0, 2); menuStrip.Padding = new Padding(5, 2, 0, 2);
menuStrip.Size = new Size(183, 24); menuStrip.Size = new Size(183, 24);
menuStrip.TabIndex = 5; menuStrip.TabIndex = 5;
this.menuStrip.TabIndex = 5;
// //
// toolStripMenuItem1 // toolStripMenuItem1
// //
@ -194,6 +196,8 @@ namespace Sailboat
ToolStripMenuItem.Name = "ToolStripMenuItem"; ToolStripMenuItem.Name = "ToolStripMenuItem";
ToolStripMenuItem.Size = new Size(48, 20); ToolStripMenuItem.Size = new Size(48, 20);
ToolStripMenuItem.Text = "Файл"; ToolStripMenuItem.Text = "Файл";
this.ToolStripMenuItem.Size = new System.Drawing.Size(59, 24);
this.ToolStripMenuItem.Text = "Файл";
// //
// SaveToolStripMenuItem // SaveToolStripMenuItem
// //
@ -218,6 +222,26 @@ namespace Sailboat
// //
saveFileDialog.Filter = "txt file | *.txt"; saveFileDialog.Filter = "txt file | *.txt";
// //
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(20, 448);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(180, 34);
this.buttonSortByType.TabIndex = 6;
this.buttonSortByType.Text = "Сортировать по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.buttonSortByType_Click);
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(20, 488);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(180, 34);
this.buttonSortByColor.TabIndex = 7;
this.buttonSortByColor.Text = "Сортировать по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.buttonSortByColor_Click);
//
// FormBoatCollection // FormBoatCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@ -260,5 +284,7 @@ namespace Sailboat
private ToolStripMenuItem LoadToolStripMenuItem; private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@ -8,10 +8,11 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Sailboat.DrawingObjects; using Sailboat.DrawingObjects;
using Sailboat.Exceptions;
using Sailboat.Generics; using Sailboat.Generics;
using Sailboat.MovementStrategy; using Sailboat.MovementStrategy;
using Sailboat.Exceptions;
namespace Sailboat namespace Sailboat
{ {
@ -30,12 +31,10 @@ namespace Sailboat
{ {
int index = listBoxStorages.SelectedIndex; int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear(); listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++) for (int i = 0; i < _storage.Keys.Count; i++)
{ {
listBoxStorages.Items.Add(_storage.Keys[i]); listBoxStorages.Items.Add(_storage.Keys[i].Name);
} }
if (listBoxStorages.Items.Count > 0 && (index == -1 || index if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count)) >= listBoxStorages.Items.Count))
{ {
@ -78,20 +77,16 @@ namespace Sailboat
_logger.LogWarning("Добавление пустого объекта"); _logger.LogWarning("Добавление пустого объекта");
return; return;
} }
try if (obj + drawingBoat != -1)
{
if (obj + drawingBoat)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBoats(); pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"Объект {obj.GetType()} добавлен"); _logger.LogInformation($"Объект {obj.GetType()} добавлен");
} }
} else
catch (StorageOverflowException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); _logger.LogInformation($"Не удалось добавить объект");
} }
} }
@ -132,6 +127,8 @@ namespace Sailboat
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}"); _logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
} }
} }
private void buttonRefreshCollection_Click(object sender, EventArgs e) private void buttonRefreshCollection_Click(object sender, EventArgs e)
@ -140,7 +137,8 @@ namespace Sailboat
{ {
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null) if (obj == null)
{ {
return; return;
@ -194,7 +192,6 @@ namespace Sailboat
_storage.SaveData(saveFileDialog.FileName); _storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}"); _logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -222,5 +219,25 @@ namespace Sailboat
} }
} }
} }
private void buttonSortByType_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByType());
private void buttonSortByColor_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByColor());
private void CompareBoats(IComparer<DrawingBoat?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowBoats();
}
} }
} }

View File

@ -174,6 +174,9 @@
this.buttonSelectBoat.Text = "Выбрать лодку"; this.buttonSelectBoat.Text = "Выбрать лодку";
this.buttonSelectBoat.UseVisualStyleBackColor = true; this.buttonSelectBoat.UseVisualStyleBackColor = true;
this.buttonSelectBoat.Click += new System.EventHandler(this.buttonSelectBoat_Click); this.buttonSelectBoat.Click += new System.EventHandler(this.buttonSelectBoat_Click);
//
// FormSailboat
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(882, 453); this.ClientSize = new System.Drawing.Size(882, 453);

View File

@ -129,7 +129,6 @@ namespace Sailboat
{ {
SelectedBoat = _drawingBoat; SelectedBoat = _drawingBoat;
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
} }
} }
} }

View File

@ -1,64 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <root>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true"> <xsd:element name="root" msdata:IsDataSet="true">