PIBD-13 Matvienko S.D. Lab-8 Simple #8

Closed
strwbrry wants to merge 2 commits from Lab-8 into Lab-7
14 changed files with 349 additions and 65 deletions

View File

@ -35,9 +35,6 @@
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>

View File

@ -32,7 +32,7 @@ namespace Catamaran.CollectionGenericObjects
public static int operator +(AbstractCompany company, DrawingBoat boat)
{
return company._collection.Insert(boat);
return company._collection.Insert(boat, new DrawingBoatEqutable());
}
public static DrawingBoat operator -(AbstractCompany company, int position)
@ -63,5 +63,7 @@ namespace Catamaran.CollectionGenericObjects
protected abstract void DrawBackground(Graphics g);
protected abstract void SetObjectsPosition();
public void Sort(IComparer<DrawingBoat?> comparer) => _collection?.CollectionSort(comparer);
}
}

View File

@ -1,4 +1,5 @@
using Catamaran.Exceptions;
using Catamaran.Drawings;
using Catamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -53,8 +54,18 @@ namespace Catamaran.CollectionGenericObjects
throw new PositionOutOfRangeException(position) ;
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
foreach (T? elem in _collection)
{
if ((comparer as IEqualityComparer<DrawingBoat>).Equals(elem as DrawingBoat, obj as DrawingBoat))
{
throw new ObjectAlreadyExistsException(elem);
}
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@ -66,8 +77,18 @@ namespace Catamaran.CollectionGenericObjects
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
foreach (T? elem in _collection)
{
if ((comparer as IEqualityComparer<DrawingBoat>).Equals(elem as DrawingBoat, obj as DrawingBoat))
{
throw new ObjectAlreadyExistsException(elem);
}
}
}
if (position > Count || position < 0)
{
throw new PositionOutOfRangeException(position);
@ -110,5 +131,10 @@ namespace Catamaran.CollectionGenericObjects
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}
}

View File

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.CollectionGenericObjects
{
public class CollectionInfo : IEquatable<CollectionInfo>
{
public string Name { get; set; }
public CollectionType CollectionType { get; private set; }
public string Description { get; set; }
private static readonly string _separator = "-";
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
}

View File

@ -0,0 +1,38 @@
using Catamaran.Drawings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.CollectionGenericObjects
{
public class DrawingBoatCompareByColor : IComparer<DrawingBoat?>
{
public int Compare(DrawingBoat? x, DrawingBoat? y)
{
if (x == null || x.EntityBoat == null)
{
return 1;
};
if (y == null || y.EntityBoat == null)
{
return -1;
}
var bodyColorCompare = x.EntityBoat.BodyColor.Name.CompareTo(y.EntityBoat.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight);
}
}
}

View File

@ -0,0 +1,34 @@
using Catamaran.Drawings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.CollectionGenericObjects
{
public class DrawingBoatCompareByType : IComparer<DrawingBoat?>
{
public int Compare(DrawingBoat? x, DrawingBoat? y)
{
if (x == null || x.EntityBoat == null)
{
return 1;
}
if (y == null || y.EntityBoat == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight);
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using Catamaran.Drawings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -13,9 +14,9 @@ namespace Catamaran.CollectionGenericObjects
int MaxCount { get; set; }
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
T? Remove(int position);
@ -24,5 +25,7 @@ namespace Catamaran.CollectionGenericObjects
CollectionType GetCollectionType { get; }
IEnumerable<T?> GetItems();
void CollectionSort(IComparer<T?> comparer);
}
}

View File

@ -1,4 +1,5 @@
using Catamaran.Exceptions;
using Catamaran.Drawings;
using Catamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -48,15 +49,29 @@ namespace Catamaran.CollectionGenericObjects
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyExistsException(obj);
}
}
_collection.Add(obj);
return 1;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyExistsException(obj);
}
}
if (position < 0 || position > Count)
{
throw new PositionOutOfRangeException(position);
@ -65,6 +80,7 @@ namespace Catamaran.CollectionGenericObjects
{
throw new CollectionOverflowException(Count);
}
_collection.Insert(position, obj);
return 1;
}
@ -87,5 +103,10 @@ namespace Catamaran.CollectionGenericObjects
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}
}

View File

@ -12,9 +12,9 @@ namespace Catamaran.CollectionGenericObjects
public class StorageCollection<T>
where T : DrawingBoat
{
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
private readonly string _collectionKey = "CollectionsStorage";
@ -24,46 +24,51 @@ namespace Catamaran.CollectionGenericObjects
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
public void AddCollection(string name, CollectionType collectionType)
{
if (!string.IsNullOrEmpty(name) && !_storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (name == null || _storages.ContainsKey(collectionInfo))
{
switch (collectionType)
return;
}
switch (collectionType)
{
case CollectionType.None:
return;
case CollectionType.Array:
_storages[name] = new ArrayGenericObjects<T>();
_storages[collectionInfo] = new ArrayGenericObjects<T>();
return;
case CollectionType.List:
_storages[name] = new ListGenericObjects<T>();
_storages[collectionInfo] = new ListGenericObjects<T>();
return;
}
}
}
public void DelCollection(string name)
{
if (string.IsNullOrEmpty(name) || !_storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
return;
_storages.Remove(collectionInfo);
}
_storages.Remove(name);
}
public ICollectionGenericObjects<T>? this[string name]
{
get
{
if (!_storages.ContainsKey(name) || string.IsNullOrEmpty(name))
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
if (!_storages.ContainsKey(collectionInfo))
{
return null;
}
return _storages[name];
return _storages[collectionInfo];
}
}
@ -82,7 +87,7 @@ namespace Catamaran.CollectionGenericObjects
using (StreamWriter writer = new(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
if (value.Value.Count == 0)
@ -92,8 +97,7 @@ namespace Catamaran.CollectionGenericObjects
writer.Write(value.Key);
writer.Write(_separatorKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorKeyValue);
@ -138,22 +142,24 @@ namespace Catamaran.CollectionGenericObjects
while ((line = reader.ReadLine()) != null)
{
string[] record = line.Split(_separatorKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
//CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию о коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ?? throw new Exception("Не удалось создать коллекцию");
if (collection == null)
{
throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingBoat() is T boat)
@ -173,7 +179,7 @@ namespace Catamaran.CollectionGenericObjects
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}

View File

@ -0,0 +1,48 @@
using Catamaran.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.Drawings
{
public class DrawingBoatEqutable : IEqualityComparer<DrawingBoat?>
{
public bool Equals(DrawingBoat? x, DrawingBoat? y)
{
if (x == null || x.EntityBoat == null) return false;
if (y == null|| y.EntityBoat == null) return false;
if (x.GetType().Name != y.GetType().Name) return false;
if (x.EntityBoat.Speed != y.EntityBoat.Speed) return false;
if (x.EntityBoat.Weight != y.EntityBoat.Weight) return false;
if (x.EntityBoat.BodyColor != y.EntityBoat.BodyColor) return false;
if (x is DrawingCatamaran && y is DrawingCatamaran)
{
EntityCatamaran CatX = (EntityCatamaran)x.EntityBoat;
EntityCatamaran CatY = (EntityCatamaran)y.EntityBoat;
if (CatX.Sail != CatY.Sail) return false;
if (CatX.LeftBobber != CatY.LeftBobber) return false;
if (CatX.RightBobber != CatY.RightBobber) return false;
if (CatX.AdditionalColor != CatY.AdditionalColor) return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawingBoat? obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.Exceptions
{
internal class ObjectAlreadyExistsException : ApplicationException
{
public ObjectAlreadyExistsException(object elem) : base("Объект уже записан в коллекции") { }
public ObjectAlreadyExistsException() : base() { }
public ObjectAlreadyExistsException(string message) : base(message) { }
public ObjectAlreadyExistsException(string message, Exception exception) : base(message, exception) { }
protected ObjectAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -52,6 +52,8 @@
LoadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonColorSort = new Button();
buttonTypeSort = new Button();
groupBox1.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelCollection.SuspendLayout();
@ -68,13 +70,15 @@
groupBox1.Dock = DockStyle.Right;
groupBox1.Location = new Point(814, 28);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(237, 646);
groupBox1.Size = new Size(237, 718);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonColorSort);
panelCompanyTools.Controls.Add(buttonTypeSort);
panelCompanyTools.Controls.Add(AddBoatButton);
panelCompanyTools.Controls.Add(UpdateButton);
panelCompanyTools.Controls.Add(maskedTextBox);
@ -82,9 +86,9 @@
panelCompanyTools.Controls.Add(DeleteButton);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 402);
panelCompanyTools.Location = new Point(3, 401);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(231, 241);
panelCompanyTools.Size = new Size(231, 314);
panelCompanyTools.TabIndex = 9;
//
// AddBoatButton
@ -99,7 +103,7 @@
//
// UpdateButton
//
UpdateButton.Location = new Point(3, 202);
UpdateButton.Location = new Point(3, 162);
UpdateButton.Name = "UpdateButton";
UpdateButton.Size = new Size(222, 38);
UpdateButton.TabIndex = 6;
@ -109,7 +113,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(3, 80);
maskedTextBox.Location = new Point(3, 41);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(222, 27);
@ -118,7 +122,7 @@
//
// GoToTestButton
//
GoToTestButton.Location = new Point(3, 158);
GoToTestButton.Location = new Point(3, 118);
GoToTestButton.Name = "GoToTestButton";
GoToTestButton.Size = new Size(222, 38);
GoToTestButton.TabIndex = 5;
@ -128,7 +132,7 @@
//
// DeleteButton
//
DeleteButton.Location = new Point(3, 113);
DeleteButton.Location = new Point(3, 74);
DeleteButton.Name = "DeleteButton";
DeleteButton.Size = new Size(222, 38);
DeleteButton.TabIndex = 4;
@ -244,7 +248,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(814, 646);
pictureBox.Size = new Size(814, 718);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -290,11 +294,31 @@
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// buttonColorSort
//
buttonColorSort.Location = new Point(3, 240);
buttonColorSort.Name = "buttonColorSort";
buttonColorSort.Size = new Size(222, 28);
buttonColorSort.TabIndex = 8;
buttonColorSort.Text = "Сортировка по цвету";
buttonColorSort.UseVisualStyleBackColor = true;
buttonColorSort.Click += buttonColorSort_Click;
//
// buttonTypeSort
//
buttonTypeSort.Location = new Point(3, 206);
buttonTypeSort.Name = "buttonTypeSort";
buttonTypeSort.Size = new Size(222, 28);
buttonTypeSort.TabIndex = 7;
buttonTypeSort.Text = "Сортировка по типу";
buttonTypeSort.UseVisualStyleBackColor = true;
buttonTypeSort.Click += buttonTypeSort_Click;
//
// FormBoatColletion
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1051, 674);
ClientSize = new Size(1051, 746);
Controls.Add(pictureBox);
Controls.Add(groupBox1);
Controls.Add(menuStrip1);
@ -339,5 +363,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonColorSort;
private Button buttonTypeSort;
}
}

View File

@ -68,6 +68,11 @@ namespace Catamaran
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Не удалось добавить объект {ex.Message}");
}
catch (ObjectAlreadyExistsException)
{
MessageBox.Show("Объект уже есть в коллекции");
_logger.LogError("Ошибка: Объект уже есть в коллекции {0}", boat);
}
}
@ -151,12 +156,12 @@ namespace Catamaran
SetBoat = boat
};
form.ShowDialog();
}
}
catch (ObjectNotFoundException)
{
_logger.LogWarning($"Не удалось найти объект для отправки на тест");
}
{
_logger.LogWarning($"Не удалось найти объект для отправки на тест");
}
}
private void RefreshListBoxItems()
@ -164,7 +169,7 @@ namespace Catamaran
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
@ -253,7 +258,7 @@ namespace Catamaran
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка сохранения: {Message}", ex.Message);
@ -281,5 +286,23 @@ namespace Catamaran
}
}
private void CompareBoats(IComparer<DrawingBoat?> comparer)
{
if (_company == null) return;
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
private void buttonTypeSort_Click(object sender, EventArgs e)
{
CompareBoats(new DrawingBoatCompareByType());
}
private void buttonColorSort_Click(object sender, EventArgs e)
{
CompareBoats(new DrawingBoatCompareByColor());
}
}
}

View File

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>