This commit is contained in:
rinat 2024-05-21 09:16:28 +04:00
parent 3499645ddb
commit 10271f7a95
11 changed files with 308 additions and 227 deletions

View File

@ -1,4 +1,6 @@
namespace WarmlyShip.CollectionGenericObjects;
using WarmlyShip.Exceptions;
namespace WarmlyShip.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : class
@ -32,7 +34,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : clas
{
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
@ -42,7 +44,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : clas
{
if (Count == _maxCount)
{
return -1;
throw new CollectionOverflowException(Count);
}
_collection.Add(obj);
return Count;
@ -52,11 +54,11 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : clas
{
if (Count == _maxCount)
{
return -1;
throw new CollectionOverflowException(Count);
}
if (position >= Count || position < 0)
{
return -1;
throw new CollectionOverflowException(Count);
}
_collection.Insert(position, obj);
return position;
@ -66,7 +68,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : clas
{
if (position >= Count || position < 0)
{
return null;
throw new PositionOutOfCollectionException(position);
}
T obj = _collection[position];
_collection.RemoveAt(position);

View File

@ -1,4 +1,7 @@
namespace WarmlyShip.CollectionGenericObjects;
using WarmlyShip.Exceptions;
using WarmlyShip.Scripts.Exceptions;
namespace WarmlyShip.CollectionGenericObjects;
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
@ -43,7 +46,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
// TODO проверка позиции
if (position < 0 || position > Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
@ -61,20 +64,15 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
// TODO проверка позиции
// TODO проверка, что элемент массима по этой позиции пустой,
// если элемент массима по этой позиции не пустой,
// найти свободное место после этой позиции, если не найдено,
// то искать до
// TODO вставка
if (position < 0 || position >= Count)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
@ -103,20 +101,22 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из массива,
// присвоив элементу массива значение null
if (position >= Count || position < 0)
{
return null;
throw new PositionOutOfCollectionException(position);
}
T obj = _collection[position];
T? obj = _collection[position];
if (obj == null)
{
throw new ObjectNotFoundException(position);
}
_collection[position] = null;
return obj;
}

View File

@ -1,5 +1,6 @@
using System.Text;
using WarmlyShip.Drawnings;
using WarmlyShip.Exceptions;
namespace WarmlyShip.CollectionGenericObjects;
@ -63,11 +64,11 @@ public class StorageCollection<T> where T : DrawningShip
return null;
}
}
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@ -112,8 +113,6 @@ public class StorageCollection<T> where T : DrawningShip
}
}
return true;
}
/// <summary>
@ -121,11 +120,11 @@ public class StorageCollection<T> where T : DrawningShip
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
@ -134,12 +133,12 @@ public class StorageCollection<T> where T : DrawningShip
if (str == null || str.Length == 0)
{
return false;
throw new IOException("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
return false;
throw new IOException("В файле неверные данные");
}
_storages.Clear();
@ -153,11 +152,8 @@ public class StorageCollection<T> where T : DrawningShip
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
}
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType) ??
throw new Exception("Не удалось определить тип коллекции: " + record[1]);
collection.MaxCount = Convert.ToInt32(record[2]);
@ -166,15 +162,21 @@ public class StorageCollection<T> where T : DrawningShip
{
if (elem?.CreateDrawningShip() is T ship)
{
if (collection.Insert(ship) == -1)
try
{
return false;
if (collection.Insert(ship) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}

View File

@ -1,15 +1,14 @@
using System.Runtime.Serialization;
namespace ProjectMonorail.Scripts.Exceptions
{
namespace WarmlyShip.Exceptions;
[Serializable]
public 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) { }
}
[Serializable]
public 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

@ -1,17 +1,14 @@
using System.Runtime.Serialization;
namespace ProjectMonorail.Scripts.Exceptions
namespace WarmlyShip.Scripts.Exceptions;
[Serializable]
public class ObjectNotFoundException : ApplicationException
{
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
public 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) { }
}
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

@ -1,15 +1,14 @@
using System.Runtime.Serialization;
namespace WarmlyShip.Exceptions
{
namespace WarmlyShip.Exceptions;
[Serializable]
public 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) { }
}
[Serializable]
public 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

@ -41,7 +41,7 @@
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMssive = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
@ -155,7 +155,7 @@
panelStoreage.Controls.Add(listBoxCollection);
panelStoreage.Controls.Add(buttonCollectionAdd);
panelStoreage.Controls.Add(radioButtonList);
panelStoreage.Controls.Add(radioButtonMssive);
panelStoreage.Controls.Add(radioButtonMassive);
panelStoreage.Controls.Add(textBoxCollectionName);
panelStoreage.Controls.Add(labelCollectionName);
panelStoreage.Dock = DockStyle.Top;
@ -204,16 +204,16 @@
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMssive
// radioButtonMassive
//
radioButtonMssive.AutoSize = true;
radioButtonMssive.Location = new Point(3, 47);
radioButtonMssive.Name = "radioButtonMssive";
radioButtonMssive.Size = new Size(67, 19);
radioButtonMssive.TabIndex = 2;
radioButtonMssive.TabStop = true;
radioButtonMssive.Text = "Массив";
radioButtonMssive.UseVisualStyleBackColor = true;
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(3, 47);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
@ -327,7 +327,7 @@
private Label labelCollectionName;
private Button buttonCollectionAdd;
private RadioButton radioButtonList;
private RadioButton radioButtonMssive;
private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName;
private Button buttonCreateCompany;
private Button buttonCollectionDel;

View File

@ -9,40 +9,48 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WarmlyShip.Drawnings;
using Microsoft.Extensions.Logging;
using WarmlyShip.Exceptions;
using WarmlyShip.Scripts.Exceptions;
namespace WarmlyShip
namespace WarmlyShip;
public partial class FormShipCollection : Form
{
public partial class FormShipCollection : Form
public FormShipCollection(ILogger<FormShipCollection> logger)
{
public FormShipCollection()
{
InitializeComponent();
_storageCollection = new();
}
private AbstractCompany? _company = null;
private readonly StorageCollection<DrawningShip> _storageCollection;
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма создалась");
}
private AbstractCompany? _company = null;
private readonly StorageCollection<DrawningShip> _storageCollection;
private readonly ILogger _logger;
private void ComboBoxSelectorCompany_SelectedIndexChanged(Object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
private void ComboBoxSelectorCompany_SelectedIndexChanged(Object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
private void ButtonAddShip_Click(object sender, EventArgs e)
{
FormShipConfig form = new();
private void ButtonAddShip_Click(object sender, EventArgs e)
{
FormShipConfig form = new();
form.Show();
form.AddEvent(SetShip);
}
form.Show();
form.AddEvent(SetShip);
}
private void SetShip(DrawningShip ship)
private void SetShip(DrawningShip ship)
{
try
{
if (_company == null || ship == null)
{
@ -53,47 +61,58 @@ namespace WarmlyShip
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Добавлен объект: " + ship.GetDataForSave());
}
}
private void ButtonRemoveShip_Click(object sender, EventArgs e)
catch (ObjectNotFoundException ex) { }
catch (CollectionOverflowException ex)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
return;
}
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
private void ButtonRemoveShip_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation("Удален объект по позиции " + pos);
}
}
private void ButtonGoToCheck_Click(object sender, EventArgs e)
catch (Exception ex)
{
if (_company == null)
{
return;
}
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
DrawningShip? ship = null;
int counter = 100;
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningShip? ship = null;
int counter = 100;
try
{
while (ship == null)
{
ship = _company.GetRandomObject();
@ -115,28 +134,34 @@ namespace WarmlyShip
};
form.ShowDialog();
}
private void ButtonRefresh_Click(object sender, EventArgs e)
catch (Exception ex)
{
if (_company == null)
{
return;
}
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
pictureBox.Image = _company.Show();
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMssive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMssive.Checked)
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
@ -147,94 +172,111 @@ namespace WarmlyShip
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
private void ButtonCollectionDel_Click(object sender, EventArgs e)
catch (Exception ex)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
}
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningShip>? collection = _storageCollection[listBoxCollection.SelectedItem?.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new PortForShips(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
_logger.LogInformation("Коллекция " + listBoxCollection.SelectedItem.ToString() + " удалена");
RefreshListBoxItems();
}
private void RefreshListBoxItems()
catch (Exception ex)
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
_logger.LogError("Ошибка: {Message}", ex.Message);
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
}
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
MessageBox.Show("Коллекция не выбрана");
return;
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
ICollectionGenericObjects<DrawningShip>? collection = _storageCollection[listBoxCollection.SelectedItem?.ToString() ?? string.Empty];
if (collection == null)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new PortForShips(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
private void RefreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
listBoxCollection.Items.Add(colName);
}
RefreshListBoxItems();
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
RefreshListBoxItems();
}
}

View File

@ -1,17 +1,31 @@
namespace WarmlyShip
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System.Drawing;
namespace WarmlyShip;
internal static class Program
{
internal static class Program
[STAThread]
static void Main()
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
ApplicationConfiguration.Initialize();
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider =
services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormShipCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormShipCollection>()
.AddLogging(option =>
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormShipCollection());
}
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}

View File

@ -8,6 +8,13 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +30,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,13 @@
<?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="shiplog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>