7 Commits

Author SHA1 Message Date
1882c9678f Merge branch 'LabWork_07' into LabWork_08_1 2023-12-24 04:36:44 +04:00
81571a348c rip 2023-12-24 04:33:08 +04:00
16da11f0e2 Merge branch 'LabWork_06' into LabWork_07 2023-12-20 10:35:51 +04:00
918be42c06 треш 2023-12-20 09:17:51 +04:00
9953e40a20 треш 2023-12-20 09:17:34 +04:00
6b440d6ada доигралась.... 2023-12-19 18:45:06 +04:00
a58085b4d1 lab 7 надеюсь готова 2023-12-19 18:27:50 +04:00
17 changed files with 544 additions and 159 deletions

View File

@@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Battleship"
}
}
}

View File

@@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Catamaran.DrawningObjects;
using Catamaran.Entities;
namespace Catamaran.Generics
{
internal class CatamaranCompareByColor : IComparer<DrawningCatamaran?>
{
public int Compare(DrawningCatamaran? x, DrawningCatamaran? y)
{
if (x == null || x.EntityCatamaran == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityCatamaran == null)
{
throw new ArgumentNullException(nameof(y));
}
var bodyColorCompare = x.EntityCatamaran.BodyColor.Name.CompareTo(y.EntityCatamaran.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x.EntityCatamaran is EntitySailCatamaran xEntitySailCatamaran && y.EntityCatamaran is EntitySailCatamaran yEntitySailCatamaran)
{
var dumpBoxColorCompare = xEntitySailCatamaran.BodyColor.Name.CompareTo(yEntitySailCatamaran.BodyColor.Name);
if (dumpBoxColorCompare != 0)
{
return dumpBoxColorCompare;
}
var tentColorCompare = xEntitySailCatamaran.AdditionalColor.Name.CompareTo(yEntitySailCatamaran.AdditionalColor.Name);
if (tentColorCompare != 0)
{
return tentColorCompare;
}
}
var speedCompare = x.EntityCatamaran.Speed.CompareTo(y.EntityCatamaran.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityCatamaran.Weight.CompareTo(y.EntityCatamaran.Weight);
}
}
}

View File

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

View File

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

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.Generics
{
internal class CatamaransCollectionInfo : IEquatable<CatamaransCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public CatamaransCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(CatamaransCollectionInfo? other)
{
if (Name == other?.Name)
return true;
return false;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@@ -41,6 +41,8 @@ namespace Catamaran.Generics
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetCatamarans => _collection.GetCatamarans();
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary>
/// Конструктор
/// </summary>
@@ -66,7 +68,7 @@ namespace Catamaran.Generics
{
return false;
}
return collect?._collection.Insert(obj) ?? false;
return (bool)collect?._collection.Insert(obj, new DrawingCatamaranEqutables());
}
/// <summary>
/// Перегрузка оператора вычитания

View File

@@ -12,12 +12,12 @@ namespace Catamaran.Generics
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, CatamaransGenericCollection<DrawningCatamaran,
readonly Dictionary<CatamaransCollectionInfo, CatamaransGenericCollection<DrawningCatamaran,
DrawningObjectCatamaran>> _catamaranStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _catamaranStorages.Keys.ToList();
public List<CatamaransCollectionInfo> Keys => _catamaranStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@@ -45,7 +45,7 @@ namespace Catamaran.Generics
/// <param name="pictureHeight"></param>
public CatamaransGenericStorage(int pictureWidth, int pictureHeight)
{
_catamaranStorages = new Dictionary<string,
_catamaranStorages = new Dictionary<CatamaransCollectionInfo,
CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
@@ -57,8 +57,7 @@ namespace Catamaran.Generics
public void AddSet(string name)
{
// TODO Прописать логику для добавления
if (_catamaranStorages.ContainsKey(name)) return;
_catamaranStorages[name] = new CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>(_pictureWidth, _pictureHeight);
_catamaranStorages.Add(new CatamaransCollectionInfo(name, string.Empty), new CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
@@ -67,9 +66,9 @@ namespace Catamaran.Generics
public void DelSet(string name)
{
// TODO Прописать логику для удаления
if (!_catamaranStorages.ContainsKey(name))
if (!_catamaranStorages.ContainsKey(new CatamaransCollectionInfo(name, string.Empty)))
return;
_catamaranStorages.Remove(name);
_catamaranStorages.Remove(new CatamaransCollectionInfo(name, string.Empty));
}
/// <summary>
/// Доступ к набору
@@ -82,8 +81,9 @@ namespace Catamaran.Generics
get
{
// TODO Продумать логику получения набора
if (_catamaranStorages.ContainsKey(ind))
return _catamaranStorages[ind];
CatamaransCollectionInfo indObj = new CatamaransCollectionInfo(ind, string.Empty);
if (_catamaranStorages.ContainsKey(indObj))
return _catamaranStorages[indObj];
return null;
}
}
@@ -92,83 +92,88 @@ namespace Catamaran.Generics
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>> record in _catamaranStorages)
foreach (KeyValuePair<CatamaransCollectionInfo, CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>> record in _catamaranStorages)
{
StringBuilder records = new();
foreach (DrawningCatamaran? elem in record.Value.GetCatamarans)
{
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("Невалидная операция, нет данных для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write($"CatamaranStorage{Environment.NewLine}{data}");
}
return true;
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"CatamaranStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return;
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не найден");
}
using (StreamReader fs = File.OpenText(filename))
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
return false;
bufferTextFromFile += temp.GetString(b);
}
if (!str.StartsWith("CatamaranStorage"))
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("Нет данных для загрузки");
}
if (!strs[0].StartsWith("CatamaranStorage"))
{
//если нет такой записи, то это не те данные
throw new Exception("Неверный формат данных");
}
_catamaranStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
return false;
continue;
}
_catamaranStorages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (strs == null)
DrawningCatamaran? catamaran =
elem?.CreateDrawningCatamaran(_separatorForObject, _pictureWidth, _pictureHeight);
if (catamaran != null)
{
return false;
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningCatamaran? catamaran = elem?.CreateDrawningCatamaran(_separatorForObject, _pictureWidth, _pictureHeight);
if (catamaran != null)
if (!(collection + catamaran))
{
if (!(collection + catamaran))
{
return false;
}
throw new Exception("Ошибка добавления в коллекцию");
}
}
_catamaranStorages.Add(record[0], collection);
}
return true;
_catamaranStorages.Add(new CatamaransCollectionInfo(record[0], string.Empty), collection);
}
}
}

View File

@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Catamaran.DrawningObjects;
using Catamaran.Entities;
namespace Catamaran.Generics
{
internal class DrawingCatamaranEqutables : IEqualityComparer<DrawningCatamaran?>
{
public bool Equals(DrawningCatamaran? x, DrawningCatamaran? y)
{
if (x == null || x.EntityCatamaran == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityCatamaran == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityCatamaran.Speed != y.EntityCatamaran.Speed)
{
return false;
}
if (x.EntityCatamaran.Weight != y.EntityCatamaran.Weight)
{
return false;
}
if (x.EntityCatamaran.BodyColor != y.EntityCatamaran.BodyColor)
{
return false;
}
if (x is DrawningSailCatamaran && y is DrawningSailCatamaran)
{
EntitySailCatamaran EntityX = (EntitySailCatamaran)x.EntityCatamaran;
EntitySailCatamaran EntityY = (EntitySailCatamaran)y.EntityCatamaran;
if (EntityX.Sail != EntityY.Sail)
return false;
if (EntityX.FloatDetail != EntityY.FloatDetail)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningCatamaran obj)
{
return obj.GetHashCode();
}
}
}

View File

@@ -45,6 +45,8 @@
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.SortByType = new System.Windows.Forms.Button();
this.SortByColor = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.groupBoxTools.SuspendLayout();
this.groupBoxSets.SuspendLayout();
@@ -61,6 +63,8 @@
//
// groupBoxTools
//
this.groupBoxTools.Controls.Add(this.SortByColor);
this.groupBoxTools.Controls.Add(this.SortByType);
this.groupBoxTools.Controls.Add(this.groupBoxSets);
this.groupBoxTools.Controls.Add(this.maskedTextBoxNumber);
this.groupBoxTools.Controls.Add(this.ButtonRefreshCollection);
@@ -80,7 +84,7 @@
this.groupBoxSets.Controls.Add(this.buttonDelObject);
this.groupBoxSets.Controls.Add(this.listBoxStorages);
this.groupBoxSets.Controls.Add(this.buttonAddObject);
this.groupBoxSets.Location = new System.Drawing.Point(3, 63);
this.groupBoxSets.Location = new System.Drawing.Point(3, 46);
this.groupBoxSets.Name = "groupBoxSets";
this.groupBoxSets.Size = new System.Drawing.Size(138, 203);
this.groupBoxSets.TabIndex = 4;
@@ -126,7 +130,7 @@
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(3, 321);
this.maskedTextBoxNumber.Location = new System.Drawing.Point(0, 351);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(137, 23);
this.maskedTextBoxNumber.TabIndex = 3;
@@ -143,7 +147,7 @@
//
// ButtonRemoveCatamaran
//
this.ButtonRemoveCatamaran.Location = new System.Drawing.Point(0, 363);
this.ButtonRemoveCatamaran.Location = new System.Drawing.Point(-1, 380);
this.ButtonRemoveCatamaran.Name = "ButtonRemoveCatamaran";
this.ButtonRemoveCatamaran.Size = new System.Drawing.Size(140, 34);
this.ButtonRemoveCatamaran.TabIndex = 1;
@@ -153,9 +157,9 @@
//
// ButtonAddCatamaran
//
this.ButtonAddCatamaran.Location = new System.Drawing.Point(3, 270);
this.ButtonAddCatamaran.Location = new System.Drawing.Point(-1, 311);
this.ButtonAddCatamaran.Name = "ButtonAddCatamaran";
this.ButtonAddCatamaran.Size = new System.Drawing.Size(137, 34);
this.ButtonAddCatamaran.Size = new System.Drawing.Size(140, 34);
this.ButtonAddCatamaran.TabIndex = 0;
this.ButtonAddCatamaran.Text = "Добавить катамаран";
this.ButtonAddCatamaran.UseVisualStyleBackColor = true;
@@ -183,14 +187,14 @@
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
@@ -198,6 +202,26 @@
//
this.openFileDialog.FileName = "openFileDialog1";
//
// SortByType
//
this.SortByType.Location = new System.Drawing.Point(-1, 255);
this.SortByType.Name = "SortByType";
this.SortByType.Size = new System.Drawing.Size(140, 23);
this.SortByType.TabIndex = 6;
this.SortByType.Text = "Сортировка по типу";
this.SortByType.UseVisualStyleBackColor = true;
this.SortByType.Click += new System.EventHandler(this.buttonSortByType_Click);
//
// SortByColor
//
this.SortByColor.Location = new System.Drawing.Point(0, 282);
this.SortByColor.Name = "SortByColor";
this.SortByColor.Size = new System.Drawing.Size(139, 23);
this.SortByColor.TabIndex = 7;
this.SortByColor.Text = "Сортировка по цвету";
this.SortByColor.UseVisualStyleBackColor = true;
this.SortByColor.Click += new System.EventHandler(this.buttonSortByColor_Click);
//
// FormCatamaranCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
@@ -238,5 +262,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button SortByColor;
private Button SortByType;
}
}

View File

@@ -1,6 +1,18 @@
using Catamaran.DrawningObjects;
using Microsoft.Extensions.Logging;
using Catamaran.DrawningObjects;
using Catamaran.Exceptions;
using Catamaran.Generics;
using Catamaran.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Catamaran
{
@@ -13,16 +25,21 @@ namespace Catamaran
/// Набор объектов
/// </summary>
private readonly CatamaransGenericStorage _storage;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormCatamaranCollection()
public FormCatamaranCollection(ILogger<FormCatamaranCollection> logger)
{
InitializeComponent();
_storage = new CatamaransGenericStorage(pictureBoxCollection.Width,pictureBoxCollection.Height);
_storage = new CatamaransGenericStorage(pictureBoxCollection.Width,
pictureBoxCollection.Height);
_logger = logger;
}
/// <summary>
/// Заполнение listBoxStorages
/// </summary>
@@ -32,7 +49,7 @@ namespace Catamaran
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))
@@ -45,7 +62,6 @@ namespace Catamaran
listBoxStorages.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
@@ -61,42 +77,51 @@ namespace Catamaran
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор:{ textBoxStorageName.Text}");
}
private void AddCatamaran(DrawningCatamaran drawningCatamaran)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
if (obj + drawningCatamaran)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowCatamarans();
}
else
{
MessageBox.Show("Не удалось добавить объект");
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого объекта");
return;
}
try
{
if (obj + drawningCatamaran)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowCatamarans();
_logger.LogInformation($"Объект добавлен");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
}
}
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxObjects_SelectedIndexChanged(object sender,
EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowCatamarans();
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowCatamarans();
}
/// <summary>
/// Удаление набора
/// </summary>
@@ -108,15 +133,15 @@ namespace Catamaran
{
return;
}
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;
if (MessageBox.Show($"Удалить объект {name}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
/// <summary>
/// Добавление объекта
/// </summary>
@@ -126,6 +151,7 @@ namespace Catamaran
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Коллекция не выбрана");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
@@ -134,11 +160,11 @@ namespace Catamaran
return;
}
var formBoatConfig = new FormCatamaranConfig();
// TODO Call method AddEvent from formCarConfig
formBoatConfig.AddEvent(AddCatamaran);
formBoatConfig.Show();
// TODO Call method AddEvent from FormCatamaranConfig
var FormCatamaranConfig = new FormCatamaranConfig();
FormCatamaranConfig.AddEvent(AddCatamaran);
FormCatamaranConfig.Show();
}
/// <summary>
/// Удаление объекта из набора
/// </summary>listBoxStorages
@@ -162,17 +188,31 @@ namespace Catamaran
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowCatamarans();
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowCatamarans();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
else
catch (CatamaranNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"Нет объекта{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
}
catch (FormatException)
{
_logger.LogWarning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
@@ -202,15 +242,16 @@ namespace Catamaran
{
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);
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
}
}
@@ -221,20 +262,41 @@ namespace Catamaran
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}
ReloadObjects();
}
ReloadObjects();
}
private void buttonSortByType_Click(object sender, EventArgs e) => CompareCatamarans(new CatamaranCompareByType());
private void CompareCatamarans(IComparer<DrawningCatamaran?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowCatamarans();
}
private void buttonSortByColor_Click(object sender, EventArgs e) => CompareCatamarans(new CatamaranCompareByColor());
}
}
}

View File

@@ -67,6 +67,6 @@
<value>254, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>96</value>
<value>25</value>
</metadata>
</root>

View File

@@ -7,6 +7,8 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Catamaran.DrawningObjects;
using Catamaran.Entities;
@@ -108,6 +110,8 @@ namespace Catamaran
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
ILogger<FormCatamaranCollection> logger = new NullLogger<FormCatamaranCollection>();
FormCatamaranCollection form = new FormCatamaranCollection(logger);
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":

View File

@@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Catamaran
{
internal static class Program
@@ -8,10 +14,31 @@ namespace Catamaran
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormCatamaranCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormCatamaranCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormCatamaranCollection>().AddLogging(option =>
{
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}appSetting.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@@ -1,4 +1,5 @@
using System;
using Catamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
@@ -26,6 +27,8 @@ namespace Catamaran.Generics
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Конструктор
/// </summary>
@@ -40,35 +43,25 @@ namespace Catamaran.Generics
/// </summary>
/// <param name="car">Добавляемый катамаран</param>
/// <returns></returns>
public bool Insert(T catamaran)
public bool Insert(T catamaran, IEqualityComparer<T?>? equal = null)
{
// TODO вставка в начало набора
if (_places.Count == _maxCount)
{
return false;
}
Insert(catamaran, 0);
return true;
return Insert(catamaran, 0, equal);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="catamaran">Добавляемый катамаран</param>
/// <param name="catamaran">Добавляемая лодка</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T catamaran, int position)
{
// TODO проверка позиции
// TODO проверка, что элемент массива по этой позиции пустой,
//если нет, то проверка, что после вставляемого элемента в массиве есть пустой элемент
// сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
// TODO вставка по позиции
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
{
return false;
}
_places.Insert(position, catamaran);
public bool Insert(T catamaran, int position, IEqualityComparer<T?>? equal = null)
{
if (position < 0 || position >= _maxCount)
throw new CatamaranNotFoundException(position);
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
if (equal != null && _places.Contains(catamaran, equal))
throw new ArgumentException("Данный объект уже есть в коллекции");
_places.Insert(0, catamaran);
return true;
}
/// <summary>
@@ -80,9 +73,13 @@ namespace Catamaran.Generics
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position < 0 || position >= Count)
{
return false;
if (position >= Count || position < 0)
{
throw new CatamaranNotFoundException("Invalid operation");
}
if (_places[position] == null)
{
throw new CatamaranNotFoundException(position);
}
_places.RemoveAt(position);
return true;

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Catamaran.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 contex) : base(info, contex) { }
}
}

View File

@@ -0,0 +1,14 @@
<?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>