This commit is contained in:
Слава 2024-06-04 02:17:26 +04:00
parent 4e4c95dc3f
commit fbe216e0f4
14 changed files with 399 additions and 194 deletions

View File

@ -1,4 +1,5 @@
using ProjectBoat.Drawnings;
using ProjectBoat.Exceptions;
namespace ProjectBoat.CollectionGenericObjects
{
@ -35,7 +36,7 @@ namespace ProjectBoat.CollectionGenericObjects
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
@ -96,8 +97,15 @@ namespace ProjectBoat.CollectionGenericObjects
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningBoat? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningBoat? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{ }
catch (PositionOutOfCollectionException e)
{ }
}
return bitmap;
}

View File

@ -1,4 +1,5 @@
using ProjectBoat.Drawnings;
using ProjectBoat.Exceptions;
namespace ProjectBoat.CollectionGenericObjects
{
@ -41,11 +42,14 @@ namespace ProjectBoat.CollectionGenericObjects
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection.Get(i) != null)
try
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
}
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException e) { }
if (curWidth < width - 1)
curWidth++;

View File

@ -1,4 +1,6 @@
namespace ProjectBoat.CollectionGenericObjects
using ProjectBoat.Exceptions;
namespace ProjectBoat.CollectionGenericObjects
{
/// <summary>
/// Параметризованный набор объектов
@ -40,15 +42,18 @@
public T? Get(int position)
{
// TODO проверка позиции
if (position >= Count || position < 0) return null;
// TODO проверка позиции
// TODO выброc позиций, если выход за границы массива
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO выбром позиций, если переполнение
// TODO вставка в конец набора
if (Count == _maxCount) return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
@ -58,8 +63,8 @@
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
if (Count == _maxCount) return -1;
if (position >= Count || position < 0) return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
@ -69,7 +74,8 @@
{
// TODO проверка позиции
// TODO удаление объекта из списка
if (position >= Count || position < 0) return null;
// TODO выбром позиций, если выход за границы массива
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;

View File

@ -1,4 +1,4 @@
using ProjectBoat.Drawnings;
using ProjectBoat.Exceptions;
namespace ProjectBoat.CollectionGenericObjects
{
@ -48,26 +48,30 @@ namespace ProjectBoat.CollectionGenericObjects
public T? Get(int position)
{
// TODO проверка позиции
if (position >= _collection.Length || position < 0)
{ return null; }
// TODO выбром позиций, если выход за границы массива
// TODO выбром позиций, если объект пустой
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
{
// TODO вставка в свободное место набора
// TODO выброc позиций, если переполнение
int index = 0;
while (index < _collection.Length)
while (index < Count && _collection[index] != null)
{
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
index++;
}
return -1;
if (index < Count)
{
_collection[index] = obj;
return index;
}
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
@ -77,45 +81,59 @@ namespace ProjectBoat.CollectionGenericObjects
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO вставка
if (position >= _collection.Length || position < 0)
{ return -1; }
// TODO выбром позиций, если переполнение
// TODO выбром позиций, если выход за границы массива
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
if (_collection[position] != null)
{
_collection[position] = obj;
return position;
}
int index;
for (index = position + 1; index < _collection.Length; ++index)
{
if (_collection[index] == null)
bool pushed = false;
for (int index = position + 1; index < Count; index++)
{
_collection[position] = obj;
return position;
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
}
}
for (index = position - 1; index >= 0; --index)
{
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
return -1;
_collection[position] = obj;
return position;
}
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0)
{ return null; }
T obj = _collection[position];
// TODO выбром позиций, если выход за границы массива
// TODO выбром позиций, если объект пустой
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null;
return obj;
return temp;
}
public IEnumerable<T?> GetItems()

View File

@ -1,4 +1,5 @@
using ProjectBoat.Drawnings;
using ProjectBoat.Exceptions;
using System.Text;
namespace ProjectBoat.CollectionGenericObjects
@ -93,78 +94,76 @@ namespace ProjectBoat.CollectionGenericObjects
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
streamWriter.Write(Environment.NewLine);
if (value.Value.Count == 0)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
continue;
}
streamWriter.Write(value.Key);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.GetCollectionType);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
streamWriter.Write(data);
streamWriter.Write(_separatorItems);
}
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// Загрузка информации по кораблям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
/// <param name="filename"></param>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
using (StreamReader sr = new StreamReader(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith(_collectionKey))
{
return false;
}
string? str;
str = sr.ReadLine();
if (str != _collectionKey.ToString())
throw new FormatException("В файле неверные данные");
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
while ((str = sr.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4)
{
continue;
@ -173,24 +172,31 @@ namespace ProjectBoat.CollectionGenericObjects
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBoat() is T boat)
if (elem?.CreateDrawningBoat() is T aircraft)
{
if (collection.Insert(boat) == -1)
try
{
return false;
if (collection.Insert(aircraft) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBoat.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBoat.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBoat.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -66,21 +66,18 @@
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(552, 24);
groupBoxTools.Margin = new Padding(3, 2, 3, 2);
groupBoxTools.Location = new Point(631, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Padding = new Padding(3, 2, 3, 2);
groupBoxTools.Size = new Size(194, 485);
groupBoxTools.Size = new Size(222, 651);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "инструменты";
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(18, 259);
buttonCreateCompany.Margin = new Padding(3, 2, 3, 2);
buttonCreateCompany.Location = new Point(21, 345);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(163, 20);
buttonCreateCompany.Size = new Size(186, 27);
buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
@ -96,18 +93,16 @@
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 18);
panelStorage.Margin = new Padding(3, 2, 3, 2);
panelStorage.Location = new Point(3, 23);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(188, 212);
panelStorage.Size = new Size(216, 283);
panelStorage.TabIndex = 6;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(15, 185);
buttonCollectionDel.Margin = new Padding(3, 2, 3, 2);
buttonCollectionDel.Location = new Point(17, 247);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(163, 20);
buttonCollectionDel.Size = new Size(186, 27);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
@ -116,19 +111,17 @@
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(15, 103);
listBoxCollection.Margin = new Padding(3, 2, 3, 2);
listBoxCollection.ItemHeight = 20;
listBoxCollection.Location = new Point(17, 137);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(163, 79);
listBoxCollection.Size = new Size(186, 104);
listBoxCollection.TabIndex = 5;
//
// buttonCollecctionAdd
//
buttonCollecctionAdd.Location = new Point(15, 78);
buttonCollecctionAdd.Margin = new Padding(3, 2, 3, 2);
buttonCollecctionAdd.Location = new Point(17, 104);
buttonCollecctionAdd.Name = "buttonCollecctionAdd";
buttonCollecctionAdd.Size = new Size(163, 20);
buttonCollecctionAdd.Size = new Size(186, 27);
buttonCollecctionAdd.TabIndex = 4;
buttonCollecctionAdd.Text = "Добавить коллекцию";
buttonCollecctionAdd.UseVisualStyleBackColor = true;
@ -137,10 +130,9 @@
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(108, 56);
radioButtonList.Margin = new Padding(3, 2, 3, 2);
radioButtonList.Location = new Point(123, 75);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19);
radioButtonList.Size = new Size(80, 24);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
@ -149,10 +141,9 @@
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(15, 56);
radioButtonMassive.Margin = new Padding(3, 2, 3, 2);
radioButtonMassive.Location = new Point(17, 75);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.Size = new Size(82, 24);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
@ -160,18 +151,17 @@
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(15, 24);
textBoxCollectionName.Margin = new Padding(3, 2, 3, 2);
textBoxCollectionName.Location = new Point(17, 32);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(163, 23);
textBoxCollectionName.Size = new Size(186, 27);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(23, 7);
labelCollectionName.Location = new Point(26, 9);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(122, 15);
labelCollectionName.Size = new Size(155, 20);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции";
//
@ -180,10 +170,9 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(18, 233);
comboBoxSelectorCompany.Margin = new Padding(3, 2, 3, 2);
comboBoxSelectorCompany.Location = new Point(21, 311);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(163, 23);
comboBoxSelectorCompany.Size = new Size(186, 28);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged_1;
//
@ -195,32 +184,29 @@
panelCompanyTools.Controls.Add(maskedTextBoxPosision);
panelCompanyTools.Controls.Add(buttonGetToTest);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 284);
panelCompanyTools.Margin = new Padding(3, 2, 3, 2);
panelCompanyTools.Location = new Point(3, 379);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(189, 206);
panelCompanyTools.Size = new Size(216, 274);
panelCompanyTools.TabIndex = 8;
//
// ButtonAddBoat
//
ButtonAddBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonAddBoat.BackgroundImageLayout = ImageLayout.Center;
ButtonAddBoat.Location = new Point(16, 2);
ButtonAddBoat.Margin = new Padding(3, 2, 3, 2);
ButtonAddBoat.Location = new Point(18, 3);
ButtonAddBoat.Name = "ButtonAddBoat";
ButtonAddBoat.Size = new Size(163, 30);
ButtonAddBoat.Size = new Size(186, 40);
ButtonAddBoat.TabIndex = 1;
ButtonAddBoat.Text = "добваление лодки";
ButtonAddBoat.Text = "добваление крейсера";
ButtonAddBoat.UseVisualStyleBackColor = true;
ButtonAddBoat.Click += ButtonAddBoat_Click;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRefresh.Location = new Point(16, 170);
buttonRefresh.Margin = new Padding(3, 2, 3, 2);
buttonRefresh.Location = new Point(18, 227);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(163, 31);
buttonRefresh.Size = new Size(186, 41);
buttonRefresh.TabIndex = 5;
buttonRefresh.Text = "обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@ -229,32 +215,29 @@
// ButtonRemoveBoat
//
ButtonRemoveBoat.Anchor = AnchorStyles.Right;
ButtonRemoveBoat.Location = new Point(16, 104);
ButtonRemoveBoat.Margin = new Padding(3, 2, 3, 2);
ButtonRemoveBoat.Location = new Point(18, 138);
ButtonRemoveBoat.Name = "ButtonRemoveBoat";
ButtonRemoveBoat.Size = new Size(163, 30);
ButtonRemoveBoat.Size = new Size(186, 40);
ButtonRemoveBoat.TabIndex = 3;
ButtonRemoveBoat.Text = "удалить лодку";
ButtonRemoveBoat.Text = "удалить крейсер";
ButtonRemoveBoat.UseVisualStyleBackColor = true;
ButtonRemoveBoat.Click += ButtonRemoveBoat_Click;
//
// maskedTextBoxPosision
//
maskedTextBoxPosision.Location = new Point(15, 79);
maskedTextBoxPosision.Margin = new Padding(3, 2, 3, 2);
maskedTextBoxPosision.Location = new Point(17, 105);
maskedTextBoxPosision.Mask = "00";
maskedTextBoxPosision.Name = "maskedTextBoxPosision";
maskedTextBoxPosision.Size = new Size(164, 23);
maskedTextBoxPosision.Size = new Size(187, 27);
maskedTextBoxPosision.TabIndex = 2;
maskedTextBoxPosision.ValidatingType = typeof(int);
//
// buttonGetToTest
//
buttonGetToTest.Anchor = AnchorStyles.Right;
buttonGetToTest.Location = new Point(16, 138);
buttonGetToTest.Margin = new Padding(3, 2, 3, 2);
buttonGetToTest.Location = new Point(18, 184);
buttonGetToTest.Name = "buttonGetToTest";
buttonGetToTest.Size = new Size(163, 30);
buttonGetToTest.Size = new Size(186, 40);
buttonGetToTest.TabIndex = 4;
buttonGetToTest.Text = "передать на тесты";
buttonGetToTest.UseVisualStyleBackColor = true;
@ -263,13 +246,11 @@
// pictureBoxBoat
//
pictureBoxBoat.Dock = DockStyle.Fill;
pictureBoxBoat.Location = new Point(0, 24);
pictureBoxBoat.Margin = new Padding(3, 2, 3, 2);
pictureBoxBoat.Location = new Point(0, 28);
pictureBoxBoat.Name = "pictureBoxBoat";
pictureBoxBoat.Size = new Size(552, 485);
pictureBoxBoat.Size = new Size(631, 651);
pictureBoxBoat.TabIndex = 1;
pictureBoxBoat.TabStop = false;
pictureBoxBoat.Click += pictureBoxBoat_Click;
//
// menuStrip
//
@ -277,8 +258,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(5, 2, 0, 2);
menuStrip.Size = new Size(746, 24);
menuStrip.Size = new Size(853, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
@ -286,14 +266,14 @@
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
@ -301,7 +281,7 @@
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
@ -315,14 +295,13 @@
//
// FormBoatsCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(746, 509);
ClientSize = new Size(853, 679);
Controls.Add(pictureBoxBoat);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Margin = new Padding(3, 2, 3, 2);
Name = "FormBoatsCollection";
Text = "FormBoatsCollection";
groupBoxTools.ResumeLayout(false);

View File

@ -1,4 +1,5 @@
using ProjectBoat.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectBoat.CollectionGenericObjects;
using ProjectBoat.Drawnings;
namespace ProjectBoat
@ -15,13 +16,19 @@ namespace ProjectBoat
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormBoatsCollection()
public FormBoatsCollection(ILogger<FormBoatsCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
@ -34,6 +41,11 @@ namespace ProjectBoat
panelCompanyTools.Enabled = false;
}
/// <summary>
/// добавление крейсера
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddBoat_Click(object sender, EventArgs e)
{
FormBoatConfing form = new();
@ -53,15 +65,18 @@ namespace ProjectBoat
{
return;
}
if (_company + boat != -1)
try
{
var res = _company + boat;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBoxBoat.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -82,14 +97,18 @@ namespace ProjectBoat
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosision.Text);
if (_company - pos != null)
try
{
MessageBox.Show("объект удален");
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBoxBoat.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("не удалось удалить объект");
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -142,8 +161,7 @@ namespace ProjectBoat
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
@ -155,8 +173,18 @@ namespace ProjectBoat
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
/// <summary>
@ -176,6 +204,7 @@ namespace ProjectBoat
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
@ -196,7 +225,7 @@ namespace ProjectBoat
}
/// <summary>
///
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
@ -207,6 +236,7 @@ namespace ProjectBoat
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningBoat>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
@ -214,15 +244,16 @@ namespace ProjectBoat
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new BoatDockingService(pictureBoxBoat.Width, pictureBoxBoat.Height, collection);
_logger.LogInformation("Компания создана");
break;
}
panelCompanyTools.Enabled = true;
}
/// <summary>
@ -234,13 +265,16 @@ namespace ProjectBoat
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@ -254,21 +288,19 @@ namespace ProjectBoat
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void pictureBoxBoat_Click(object sender, EventArgs e)
{
}
}
}

View File

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

View File

@ -8,4 +8,15 @@
<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.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<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>
</Project>

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="boatlog-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

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": "boat"
}
}
}