6 Commits
laba6 ... lab_8

Author SHA1 Message Date
Alenka
72dcd86427 Done 2023-12-23 15:46:22 +04:00
Alenka
0f3e9f9a46 Done 2023-12-23 15:06:55 +04:00
Alenka
b6611a468c Done 2023-12-22 20:40:39 +04:00
Alenka
c4dca02f50 Начинать всегда стоит с того, что сеет сомнения 2023-12-22 20:33:02 +04:00
Alenka
bd31bcb20c Done 2023-12-08 22:08:43 +04:00
Alenka
03ebc0d612 Done 2023-12-08 21:45:56 +04:00
16 changed files with 459 additions and 117 deletions

View File

@@ -8,6 +8,18 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -0,0 +1,24 @@
using Cruiser.Generics;
namespace Cruiser
{
internal class CruiserCollectionInfo : IEquatable<CruiserCollectionInfo?>
{
public string Name { get; private set; }
public string Description { get; private set; }
public CruiserCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(CruiserCollectionInfo? other)
{
if (other == null || other.Name == null)
throw new ArgumentNullException(nameof(other));
return Name == other.Name;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@@ -0,0 +1,32 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.DrawningObjects;
using Cruiser.Entities;
namespace Cruiser.Generics
{
internal class CruiserCompareByColor : IComparer<DrawningCruiser>
{
public int Compare(DrawningCruiser? x, DrawningCruiser? y)
{
if (x == null || x.EntityCruiser == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityCruiser == null)
throw new ArgumentNullException(nameof(y));
var xCruiser = x.EntityCruiser;
var yCruiser = y.EntityCruiser;
if (xCruiser.BodyColor != yCruiser.BodyColor)
return xCruiser.BodyColor.Name.CompareTo(yCruiser.BodyColor.Name);
var speedCompare = x.EntityCruiser.Speed.CompareTo(y.EntityCruiser.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityCruiser.Weight.CompareTo(y.EntityCruiser.Weight);
}
}
}

View File

@@ -0,0 +1,28 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.DrawningObjects;
namespace Cruiser.Generics
{
internal class CruiserCompareByType : IComparer<DrawningCruiser>
{
public int Compare(DrawningCruiser? x, DrawningCruiser? y)
{
if (x == null || x.EntityCruiser == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityCruiser == null)
throw new ArgumentNullException(nameof(y));
if (x.GetType().Name != y.GetType().Name)
return x.GetType().Name.CompareTo(y.GetType().Name);
var speedCompare = x.EntityCruiser.Speed.CompareTo(y.EntityCruiser.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityCruiser.Weight.CompareTo(y.EntityCruiser.Weight);
}
}
}

View File

@@ -11,15 +11,16 @@ using Cruiser.MovementStrategy;
namespace Cruiser.Generics
{
internal class CruiserGenericCollection<T, U>
where T : DrawningCruiser
where U : IMoveableObject
{
public IEnumerable<T?> GetCruiser => _collection.GetCruiser();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private readonly int _placeSizeWidth = 210;
private readonly int _placeSizeHeight = 90;
private readonly int _placeSizeWidth = 170;
private readonly int _placeSizeHeight = 200;
private readonly SetGeneric<T> _collection;
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
public CruiserGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
@@ -28,26 +29,19 @@ namespace Cruiser.Generics
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
public static bool operator +(CruiserGenericCollection<T, U> collect, T? obj)
public static bool operator +(CruiserGenericCollection<T, U>? collect, T? obj)
{
if (obj == null)
{
if (obj == null || collect == null)
return false;
}
return collect?._collection.Insert(obj) ?? false;
collect?._collection.Insert(obj, new DrawningCruiserEqutables());
return true;
}
public static T? operator -(CruiserGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos);
}
collect._collection.Remove(pos);
return obj;
}
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
@@ -84,13 +78,12 @@ namespace Cruiser.Generics
if (cruiser != null)
{
int inRow = _pictureWidth / _placeSizeWidth;
cruiser.SetPosition((i % inRow) * _placeSizeWidth + _placeSizeWidth / 20, _placeSizeHeight * (i / inRow) + _placeSizeHeight / 10);
cruiser.SetPosition(_pictureWidth - _placeSizeWidth - (i % inRow * _placeSizeWidth) - _placeSizeHeight / 2 - 8, i / inRow * _placeSizeHeight + 20);
cruiser.DrawTransport(g);
}
i++;
}
}
public IEnumerable<T?> GetCruisers => _collection.GetCruiser();
}
}

View File

@@ -10,9 +10,9 @@ namespace Cruiser.Generics
{
internal class CruiserGenericStorage
{
readonly Dictionary<string, CruiserGenericCollection<DrawningCruiser,
readonly Dictionary<CruiserCollectionInfo, CruiserGenericCollection<DrawningCruiser,
DrawningObjectCruiser>> _cruiserStorages;
public List<string> Keys => _cruiserStorages.Keys.ToList();
public List<CruiserCollectionInfo> Keys => _cruiserStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private static readonly char _separatorForKeyValue = '|';
@@ -20,73 +20,64 @@ namespace Cruiser.Generics
private static readonly char _separatorForObject = ':';
public CruiserGenericStorage(int pictureWidth, int pictureHeight)
{
_cruiserStorages = new Dictionary<string, CruiserGenericCollection<DrawningCruiser, DrawningObjectCruiser>>();
_cruiserStorages = new Dictionary<CruiserCollectionInfo, CruiserGenericCollection<DrawningCruiser, DrawningObjectCruiser>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(string name)
{
_cruiserStorages.Add(name, new CruiserGenericCollection<DrawningCruiser, DrawningObjectCruiser>(_pictureWidth, _pictureHeight));
_cruiserStorages.Add(new CruiserCollectionInfo(name, string.Empty), new CruiserGenericCollection<DrawningCruiser, DrawningObjectCruiser>(_pictureWidth, _pictureHeight));
}
public void DelSet(string name)
{
if (!_cruiserStorages.ContainsKey(name))
if (!_cruiserStorages.ContainsKey(new CruiserCollectionInfo(name, string.Empty)));
{
return;
}
_cruiserStorages.Remove(name);
_cruiserStorages.Remove(new CruiserCollectionInfo(name, string.Empty));
}
public CruiserGenericCollection<DrawningCruiser, DrawningObjectCruiser>? this[string ind]
{
get
{
if (_cruiserStorages.ContainsKey(ind))
{
return _cruiserStorages[ind];
}
CruiserCollectionInfo indObj = new CruiserCollectionInfo(ind, string.Empty);
if (_cruiserStorages.ContainsKey(indObj))
return _cruiserStorages[indObj];
return null;
}
}
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, CruiserGenericCollection<DrawningCruiser, DrawningObjectCruiser>> record in _cruiserStorages)
foreach (KeyValuePair<CruiserCollectionInfo, CruiserGenericCollection<DrawningCruiser, DrawningObjectCruiser>> record in _cruiserStorages)
{
StringBuilder records = new();
foreach (DrawningCruiser? elem in record.Value.GetCruiser)
foreach (DrawningCruiser? elem in record.Value.GetCruisers)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
throw new Exception("Невалидная операция, нет данных для сохранения");
}
string toWrite = $"CruiserStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
using (StreamWriter sw = new(filename))
{
foreach (var str in strs)
{
sw.WriteLine(str);
}
sw.WriteLine($"PlaneStorage{Environment.NewLine}{data}");
}
return true;
return;
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new IOException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
@@ -94,11 +85,11 @@ namespace Cruiser.Generics
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
throw new IOException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("CruiserStorage"))
if (!strs[0].StartsWith("PlaneStorage"))
{
return false;
throw new IOException("Неверный формат данных");
}
_cruiserStorages.Clear();
do
@@ -110,25 +101,24 @@ namespace Cruiser.Generics
continue;
}
CruiserGenericCollection<DrawningCruiser, DrawningObjectCruiser> 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)
{
DrawningCruiser? cruiser =
elem?.CreateDrawningCruiser(_separatorForObject, _pictureWidth, _pictureHeight);
DrawningCruiser? cruiser = elem?.CreateDrawningCruiser(_separatorForObject, _pictureWidth, _pictureHeight);
if (cruiser != null)
{
if (!(collection + cruiser))
{
return false;
throw new ArgumentNullException("Ошибка добавления в коллекцию");
}
}
}
_cruiserStorages.Add(record[0], collection);
_cruiserStorages.Add(new CruiserCollectionInfo(record[0], string.Empty), collection);
str = sr.ReadLine();
} while (str != null);
}
return true;
return;
}
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Cruiser.Exceptions
{
[Serializable]
internal class CruiserNotFoundException : ApplicationException
{
public CruiserNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public CruiserNotFoundException() : base() { }
public CruiserNotFoundException(string message) : base(message) { }
public CruiserNotFoundException(string message, Exception exception) : base(message, exception) { }
protected CruiserNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -0,0 +1,57 @@
using Cruiser.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.DrawningObjects;
namespace Cruiser
{
internal class DrawingCruiserEqutables : IEqualityComparer<DrawningCruiser?>
{
public bool Equals(DrawningCruiser? x, DrawningCruiser? y)
{
if (x == null || x.EntityCruiser == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityCruiser == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityCruiser.Speed != y.EntityCruiser.Speed)
{
return false;
}
if (x.EntityCruiser.Weight != y.EntityCruiser.Weight)
{
return false;
}
if (x.EntityCruiser.BodyColor != y.EntityCruiser.BodyColor)
{
return false;
}
if (x is DrawningAdvancedCruiser && y is DrawningAdvancedCruiser)
{
EntityAdvancedCruiser EntityX = (EntityAdvancedCruiser)x.EntityCruiser;
EntityAdvancedCruiser EntityY = (EntityAdvancedCruiser)y.EntityCruiser;
if (EntityX.HelicopterPad != EntityY.HelicopterPad)
return false;
if (EntityX.Coating != EntityY.Coating)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningCruiser? obj)
{
return obj.GetHashCode();
}
}
}

View File

@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.DrawningObjects;
using Cruiser.Entities;
namespace Cruiser
{
internal class DrawningCruiserEqutables : IEqualityComparer<DrawningCruiser?>
{
public bool Equals(DrawningCruiser? x, DrawningCruiser? y)
{
if (x == null || x.EntityCruiser == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityCruiser == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityCruiser.Speed != y.EntityCruiser.Speed)
{
return false;
}
if (x.EntityCruiser.Weight != y.EntityCruiser.Weight)
{
return false;
}
if (x.EntityCruiser.BodyColor != y.EntityCruiser.BodyColor)
{
return false;
}
if (x is DrawningAdvancedCruiser && y is DrawningAdvancedCruiser)
{
EntityAdvancedCruiser EntityX = (EntityAdvancedCruiser)x.EntityCruiser;
EntityAdvancedCruiser EntityY = (EntityAdvancedCruiser)y.EntityCruiser;
if (EntityX.HelicopterPad != EntityY.HelicopterPad)
return false;
if (EntityX.Coating != EntityY.Coating)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningCruiser? obj)
{
return obj.GetHashCode();
}
}
}

View File

@@ -22,6 +22,5 @@ namespace Cruiser.Entities
{
BodyColor = color;
}
}
}

View File

@@ -32,6 +32,8 @@
this.FileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.buttonSortByType = new System.Windows.Forms.Button();
this.buttonSortByColor = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCruiser)).BeginInit();
this.panelCruiser.SuspendLayout();
this.panelSet.SuspendLayout();
@@ -43,26 +45,28 @@
this.pictureBoxCruiser.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxCruiser.Location = new System.Drawing.Point(0, 33);
this.pictureBoxCruiser.Name = "pictureBoxCruiser";
this.pictureBoxCruiser.Size = new System.Drawing.Size(904, 477);
this.pictureBoxCruiser.Size = new System.Drawing.Size(1083, 556);
this.pictureBoxCruiser.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBoxCruiser.TabIndex = 0;
this.pictureBoxCruiser.TabStop = false;
//
// panelCruiser
//
this.panelCruiser.Controls.Add(this.buttonSortByColor);
this.panelCruiser.Controls.Add(this.buttonSortByType);
this.panelCruiser.Controls.Add(this.ButtonRefreshCollection);
this.panelCruiser.Controls.Add(this.ButtonRemoveCruiser);
this.panelCruiser.Controls.Add(this.textBoxCruiser);
this.panelCruiser.Controls.Add(this.ButtonAddCruiser);
this.panelCruiser.Controls.Add(this.panelSet);
this.panelCruiser.Location = new System.Drawing.Point(655, 12);
this.panelCruiser.Location = new System.Drawing.Point(786, 36);
this.panelCruiser.Name = "panelCruiser";
this.panelCruiser.Size = new System.Drawing.Size(221, 486);
this.panelCruiser.Size = new System.Drawing.Size(221, 553);
this.panelCruiser.TabIndex = 1;
//
// ButtonRefreshCollection
//
this.ButtonRefreshCollection.Location = new System.Drawing.Point(45, 435);
this.ButtonRefreshCollection.Location = new System.Drawing.Point(45, 500);
this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRefreshCollection.Size = new System.Drawing.Size(138, 41);
this.ButtonRefreshCollection.TabIndex = 2;
@@ -72,7 +76,7 @@
//
// ButtonRemoveCruiser
//
this.ButtonRemoveCruiser.Location = new System.Drawing.Point(45, 391);
this.ButtonRemoveCruiser.Location = new System.Drawing.Point(45, 456);
this.ButtonRemoveCruiser.Name = "ButtonRemoveCruiser";
this.ButtonRemoveCruiser.Size = new System.Drawing.Size(138, 38);
this.ButtonRemoveCruiser.TabIndex = 2;
@@ -82,7 +86,7 @@
//
// textBoxCruiser
//
this.textBoxCruiser.Location = new System.Drawing.Point(45, 330);
this.textBoxCruiser.Location = new System.Drawing.Point(50, 419);
this.textBoxCruiser.Name = "textBoxCruiser";
this.textBoxCruiser.Size = new System.Drawing.Size(133, 31);
this.textBoxCruiser.TabIndex = 3;
@@ -161,7 +165,7 @@
this.FileToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(904, 33);
this.menuStrip.Size = new System.Drawing.Size(1083, 33);
this.menuStrip.TabIndex = 2;
this.menuStrip.Text = "menuStrip";
//
@@ -177,22 +181,42 @@
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(270, 34);
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(200, 34);
this.SaveToolStripMenuItem.Text = "Сохранить";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(270, 34);
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(200, 34);
this.LoadToolStripMenuItem.Text = "Загрузить";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(50, 320);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(128, 33);
this.buttonSortByType.TabIndex = 4;
this.buttonSortByType.Text = "Сортировка по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(50, 372);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(133, 27);
this.buttonSortByColor.TabIndex = 5;
this.buttonSortByColor.Text = "Сортировка по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// FormCruiserCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(904, 510);
this.ClientSize = new System.Drawing.Size(1083, 589);
this.Controls.Add(this.panelCruiser);
this.Controls.Add(this.pictureBoxCruiser);
this.Controls.Add(this.menuStrip);
@@ -229,5 +253,7 @@
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@@ -9,6 +9,10 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Cruiser.Exceptions;
using System.Xml.Linq;
using Serilog;
using System.Numerics;
namespace Cruiser
{
@@ -28,7 +32,7 @@ namespace Cruiser
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))
@@ -50,6 +54,7 @@ namespace Cruiser
}
_storage.AddSet(textBoxSet.Text);
ReloadObjects();
Log.Information($"Добавлен набор: {textBoxSet.Text}");
}
private void listBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
@@ -64,9 +69,10 @@ namespace Cruiser
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
_storage.DelSet(name);
ReloadObjects();
Log.Information($"Удален набор: {name}");
}
}
private void ButtonAddCruiser_Click(object sender, EventArgs e)
@@ -84,16 +90,22 @@ namespace Cruiser
form.Show();
Action<DrawningCruiser>? cruiserDelegate = new((m) =>
{
bool isAdditionSuccessful = (obj + m);
if (isAdditionSuccessful)
try
{
bool q = obj + m;
MessageBox.Show("Объект добавлен");
m.ChangePictureBoxSize(pictureBoxCruiser.Width, pictureBoxCruiser.Height);
pictureBoxCruiser.Image = obj.ShowCruisers();
Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
}
catch (ArgumentException)
{
Log.Warning($"Добавляемый объект уже существует в коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show("Добавляемый объект уже сущесвует в коллекции");
}
});
form.AddEvent(cruiserDelegate);
@@ -115,16 +127,25 @@ namespace Cruiser
{
return;
}
int pos = Convert.ToInt32(textBoxCruiser.Text);
if (obj - pos != null)
try
{
int pos = Convert.ToInt32(textBoxCruiser.Text);
var q = obj - pos;
MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCruiser.Image = obj.ShowCruisers();
}
else
catch (CruiserNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch (FormatException)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
@@ -144,13 +165,17 @@ namespace Cruiser
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
Log.Warning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@@ -159,19 +184,43 @@ namespace Cruiser
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
ReloadObjects();
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareCruiser(new CruiserCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareCruiser(new CruiserCompareByColor());
private void CompareCruiser(IComparer<DrawningCruiser?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCruiser.Image = obj.ShowCruisers();
}
}
}

View File

@@ -1,16 +1,40 @@
using Serilog;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Configuration;
using Microsoft.Extensions.Configuration;
namespace Cruiser
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}appsettings.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormCruiserCollection());
}
}

View File

@@ -1,8 +1,11 @@
using System;
using Cruiser.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.Exceptions;
using System.Numerics;
namespace Cruiser.Generics
{
@@ -10,60 +13,54 @@ namespace Cruiser.Generics
where T : class
{
private readonly List<T?> _places;
public int Count => _places.Count;
private readonly int _maxCount;
public int Count => _places.Count;
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
public bool Insert(T cruiser)
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
public void Insert(T cruiser, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
{
return false;
}
Insert(cruiser, 0);
return true;
throw new StorageOverflowException(_maxCount);
Insert(cruiser, 0, equal);
}
public bool Insert(T cruiser, int position)
public void Insert(T cruiser, int position, IEqualityComparer<T>? equal = null)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
throw new Exception("Неверная позиция для вставки");
if (equal != null)
{
return false;
if (_places.Contains(cruiser, equal))
throw new ArgumentException(nameof(cruiser));
}
_places.Insert(position, cruiser);
return true;
}
public bool Remove(int position)
public void Remove(int position)
{
if (position < 0 || position >= Count)
{
return false;
}
if (!(position >= 0 && position < Count))
throw new CruiserNotFoundException(position);
_places.RemoveAt(position);
return true;
}
public T? this[int position]
{
get
{
if (position < 0 || position >= _maxCount)
{
if (!(position >= 0 && position < Count))
return null;
}
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
{
return;
}
_places.Insert(position, value);
return;
}
}
public IEnumerable<T?> GetCruiser(int? maxCruisers = null)

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}