Второй этап Lab_8
This commit is contained in:
parent
01b12c835a
commit
dcb622b7d5
@ -41,6 +41,8 @@ namespace Sailboat.Generics
|
||||
/// Получение объектов коллекции
|
||||
/// </summary>
|
||||
public IEnumerable<T?> GetBoats => _collection.GetBoats();
|
||||
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
@ -60,13 +62,13 @@ namespace Sailboat.Generics
|
||||
/// <param name="collect"></param>
|
||||
/// <param name="obj"></param>
|
||||
/// <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)
|
||||
{
|
||||
return false;
|
||||
return -1;
|
||||
}
|
||||
return (bool)collect?._collection.Insert(obj);
|
||||
return collect._collection.Insert(obj, new DrawingBoatEqutables());
|
||||
}
|
||||
/// <summary>
|
||||
/// Перегрузка оператора вычитания
|
||||
@ -74,14 +76,11 @@ namespace Sailboat.Generics
|
||||
/// <param name="collect"></param>
|
||||
/// <param name="pos"></param>
|
||||
/// <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];
|
||||
if (obj != null)
|
||||
{
|
||||
}
|
||||
collect._collection.Remove(pos);
|
||||
return false;
|
||||
return obj;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -5,6 +5,7 @@ using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Sailboat.DrawingObjects;
|
||||
using Sailboat.MovementStrategy;
|
||||
using Sailboat.Exceptions;
|
||||
|
||||
namespace Sailboat.Generics
|
||||
{
|
||||
@ -13,11 +14,11 @@ namespace Sailboat.Generics
|
||||
/// <summary>
|
||||
/// Словарь (хранилище)
|
||||
/// </summary>
|
||||
readonly Dictionary<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> _boatStorages;
|
||||
readonly Dictionary<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> _boatStorages;
|
||||
/// <summary>
|
||||
/// Возвращение списка названий наборов
|
||||
/// </summary>
|
||||
public List<string> Keys => _boatStorages.Keys.ToList();
|
||||
public List<BoatsCollectionInfo> Keys => _boatStorages.Keys.ToList();
|
||||
/// <summary>
|
||||
/// Ширина окна отрисовки
|
||||
/// </summary>
|
||||
@ -45,8 +46,7 @@ namespace Sailboat.Generics
|
||||
/// <param name="pictureHeight"></param>
|
||||
public BoatsGenericStorage(int pictureWidth, int pictureHeight)
|
||||
{
|
||||
_boatStorages = new Dictionary<string,
|
||||
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
|
||||
_boatStorages = new Dictionary<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
|
||||
_pictureWidth = pictureWidth;
|
||||
_pictureHeight = pictureHeight;
|
||||
}
|
||||
@ -56,11 +56,7 @@ namespace Sailboat.Generics
|
||||
/// <param name="name">Название набора</param>
|
||||
public void AddSet(string name)
|
||||
{
|
||||
if (_boatStorages.ContainsKey(name))
|
||||
{
|
||||
return;
|
||||
}
|
||||
_boatStorages[name] = new BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>(_pictureWidth, _pictureHeight);
|
||||
_boatStorages.Add(new BoatsCollectionInfo(name, string.Empty), new BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>(_pictureWidth, _pictureHeight));
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление набора
|
||||
@ -68,26 +64,22 @@ namespace Sailboat.Generics
|
||||
/// <param name="name">Название набора</param>
|
||||
public void DelSet(string name)
|
||||
{
|
||||
if (!_boatStorages.ContainsKey(name))
|
||||
{
|
||||
if (!_boatStorages.ContainsKey(new BoatsCollectionInfo(name, string.Empty)))
|
||||
return;
|
||||
}
|
||||
_boatStorages.Remove(name);
|
||||
_boatStorages.Remove(new BoatsCollectionInfo(name, string.Empty));
|
||||
}
|
||||
/// <summary>
|
||||
/// Доступ к набору
|
||||
/// </summary>
|
||||
/// <param name="ind"></param>
|
||||
/// <returns></returns>
|
||||
public BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>?
|
||||
this[string ind]
|
||||
public BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>? this[string ind]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_boatStorages.ContainsKey(ind))
|
||||
{
|
||||
return _boatStorages[ind];
|
||||
}
|
||||
BoatsCollectionInfo indObj = new BoatsCollectionInfo(ind, string.Empty);
|
||||
if (_boatStorages.ContainsKey(indObj))
|
||||
return _boatStorages[indObj];
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -96,32 +88,36 @@ namespace Sailboat.Generics
|
||||
/// Сохранение информации по лодкам в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
public bool SaveData(string filename)
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
|
||||
StringBuilder data = new();
|
||||
foreach (KeyValuePair<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> record in _boatStorages)
|
||||
foreach (KeyValuePair<BoatsCollectionInfo, 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}");
|
||||
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
|
||||
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
throw new Exception("Невалидная операция, нет данных для сохранения");
|
||||
throw new InvalidOperationException("Файл не найден, невалидная операция, нет данных для сохранения");
|
||||
}
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
{
|
||||
writer.Write($"SailboatStorage{Environment.NewLine}{data}");
|
||||
writer.WriteLine("BoatStorage");
|
||||
writer.Write(data.ToString());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по лодкам в хранилище из файла
|
||||
/// </summary>
|
||||
@ -131,55 +127,43 @@ namespace Sailboat.Generics
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new Exception("Файл не найден");
|
||||
throw new FileNotFoundException("Файл не найден");
|
||||
}
|
||||
|
||||
string bufferTextFromFile = "";
|
||||
using (FileStream fs = new(filename, FileMode.Open))
|
||||
using (StreamReader sr = new(filename))
|
||||
{
|
||||
byte[] b = new byte[fs.Length];
|
||||
UTF8Encoding temp = new(true);
|
||||
while (fs.Read(b, 0, b.Length) > 0)
|
||||
string str = sr.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
bufferTextFromFile += temp.GetString(b);
|
||||
throw new NullReferenceException("Нет данных для загрузки");
|
||||
}
|
||||
}
|
||||
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
if (strs == null || strs.Length == 0)
|
||||
if (!str.StartsWith("BoatStorage"))
|
||||
{
|
||||
throw new Exception("Нет данных для загрузки");
|
||||
throw new InvalidDataException("Неверный формат данных");
|
||||
}
|
||||
if (!strs[0].StartsWith("BoatStorage"))
|
||||
{
|
||||
//если нет такой записи, то это не те данные
|
||||
throw new Exception("Неверный формат данных");
|
||||
}
|
||||
|
||||
_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)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat> collection = new(_pictureWidth, _pictureHeight);
|
||||
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);
|
||||
if (boat != null)
|
||||
DrawingBoat? truck = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
26
Sailboat/Sailboat/FormBoatCollection.Designer.cs
generated
26
Sailboat/Sailboat/FormBoatCollection.Designer.cs
generated
@ -77,6 +77,7 @@ namespace Sailboat
|
||||
panelTools.Name = "panelTools";
|
||||
panelTools.Size = new Size(183, 542);
|
||||
panelTools.TabIndex = 1;
|
||||
this.panelTools.TabIndex = 1;
|
||||
//
|
||||
// panelCollection
|
||||
//
|
||||
@ -182,6 +183,7 @@ namespace Sailboat
|
||||
menuStrip.Padding = new Padding(5, 2, 0, 2);
|
||||
menuStrip.Size = new Size(183, 24);
|
||||
menuStrip.TabIndex = 5;
|
||||
this.menuStrip.TabIndex = 5;
|
||||
//
|
||||
// toolStripMenuItem1
|
||||
//
|
||||
@ -194,6 +196,8 @@ namespace Sailboat
|
||||
ToolStripMenuItem.Name = "ToolStripMenuItem";
|
||||
ToolStripMenuItem.Size = new Size(48, 20);
|
||||
ToolStripMenuItem.Text = "Файл";
|
||||
this.ToolStripMenuItem.Size = new System.Drawing.Size(59, 24);
|
||||
this.ToolStripMenuItem.Text = "Файл";
|
||||
//
|
||||
// SaveToolStripMenuItem
|
||||
//
|
||||
@ -218,6 +222,26 @@ namespace Sailboat
|
||||
//
|
||||
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
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
@ -260,5 +284,7 @@ namespace Sailboat
|
||||
private ToolStripMenuItem LoadToolStripMenuItem;
|
||||
private OpenFileDialog openFileDialog;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private Button buttonSortByColor;
|
||||
private Button buttonSortByType;
|
||||
}
|
||||
}
|
@ -8,10 +8,11 @@ using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
using Sailboat.DrawingObjects;
|
||||
using Sailboat.Exceptions;
|
||||
using Sailboat.Generics;
|
||||
using Sailboat.MovementStrategy;
|
||||
using Sailboat.Exceptions;
|
||||
|
||||
namespace Sailboat
|
||||
{
|
||||
@ -30,12 +31,10 @@ namespace Sailboat
|
||||
{
|
||||
int index = listBoxStorages.SelectedIndex;
|
||||
listBoxStorages.Items.Clear();
|
||||
|
||||
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
|
||||
>= listBoxStorages.Items.Count))
|
||||
{
|
||||
@ -78,20 +77,16 @@ namespace Sailboat
|
||||
_logger.LogWarning("Добавление пустого объекта");
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (obj + drawingBoat)
|
||||
if (obj + drawingBoat != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowBoats();
|
||||
_logger.LogInformation($"Объект {obj.GetType()} добавлен");
|
||||
|
||||
}
|
||||
}
|
||||
catch (StorageOverflowException ex)
|
||||
else
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogInformation($"Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
|
||||
@ -132,6 +127,8 @@ namespace Sailboat
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void buttonRefreshCollection_Click(object sender, EventArgs e)
|
||||
@ -140,7 +137,8 @@ namespace Sailboat
|
||||
{
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
|
||||
string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
return;
|
||||
@ -194,7 +192,6 @@ namespace Sailboat
|
||||
_storage.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
|
||||
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
3
Sailboat/Sailboat/FormSailboat.Designer.cs
generated
3
Sailboat/Sailboat/FormSailboat.Designer.cs
generated
@ -174,6 +174,9 @@
|
||||
this.buttonSelectBoat.Text = "Выбрать лодку";
|
||||
this.buttonSelectBoat.UseVisualStyleBackColor = true;
|
||||
this.buttonSelectBoat.Click += new System.EventHandler(this.buttonSelectBoat_Click);
|
||||
//
|
||||
// FormSailboat
|
||||
//
|
||||
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
|
||||
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
|
||||
this.ClientSize = new System.Drawing.Size(882, 453);
|
||||
|
@ -129,7 +129,6 @@ namespace Sailboat
|
||||
{
|
||||
SelectedBoat = _drawingBoat;
|
||||
DialogResult = DialogResult.OK;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
@ -1,64 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<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.
|
||||
-->
|
||||
<root>
|
||||
<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:element name="root" msdata:IsDataSet="true">
|
||||
|
Loading…
Reference in New Issue
Block a user