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]);
@ -165,16 +161,22 @@ public class StorageCollection<T> where T : DrawningShip
foreach (string elem in set)
{
if (elem?.CreateDrawningShip() is T ship)
{
try
{
if (collection.Insert(ship) == -1)
{
return false;
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}

View File

@ -1,7 +1,7 @@
using System.Runtime.Serialization;
namespace ProjectMonorail.Scripts.Exceptions
{
namespace WarmlyShip.Exceptions;
[Serializable]
public class CollectionOverflowException : ApplicationException
@ -12,4 +12,3 @@ namespace ProjectMonorail.Scripts.Exceptions
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -1,10 +1,8 @@
using System.Runtime.Serialization;
namespace ProjectMonorail.Scripts.Exceptions
{
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
namespace WarmlyShip.Scripts.Exceptions;
[Serializable]
public class ObjectNotFoundException : ApplicationException
{
@ -14,4 +12,3 @@ namespace ProjectMonorail.Scripts.Exceptions
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -1,7 +1,7 @@
using System.Runtime.Serialization;
namespace WarmlyShip.Exceptions
{
namespace WarmlyShip.Exceptions;
[Serializable]
public class PositionOutOfCollectionException : ApplicationException
@ -12,4 +12,3 @@ namespace WarmlyShip.Exceptions
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,18 +9,24 @@ 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 FormShipCollection()
public FormShipCollection(ILogger<FormShipCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма создалась");
}
private AbstractCompany? _company = null;
private readonly StorageCollection<DrawningShip> _storageCollection;
private readonly ILogger _logger;
@ -43,6 +49,8 @@ namespace WarmlyShip
private void SetShip(DrawningShip ship)
{
try
{
if (_company == null || ship == null)
{
@ -53,10 +61,14 @@ namespace WarmlyShip
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + ship.GetDataForSave());
}
else
}
catch (ObjectNotFoundException ex) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -74,14 +86,19 @@ namespace WarmlyShip
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
else
}
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -94,6 +111,8 @@ namespace WarmlyShip
DrawningShip? ship = null;
int counter = 100;
try
{
while (ship == null)
{
ship = _company.GetRandomObject();
@ -115,6 +134,11 @@ namespace WarmlyShip
};
form.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonRefresh_Click(object sender, EventArgs e)
{
@ -129,14 +153,15 @@ namespace WarmlyShip
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMssive.Checked))
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMssive.Checked)
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
@ -147,6 +172,12 @@ namespace WarmlyShip
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void ButtonCollectionDel_Click(object sender, EventArgs e)
@ -156,14 +187,21 @@ namespace WarmlyShip
MessageBox.Show("Коллекция не выбрана");
return;
}
try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция " + listBoxCollection.SelectedItem.ToString() + " удалена");
RefreshListBoxItems();
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -209,13 +247,16 @@ namespace WarmlyShip
{
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);
}
}
}
@ -224,17 +265,18 @@ namespace WarmlyShip
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
else
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
{
/// <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();
Application.Run(new FormShipCollection());
}
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 =>
{
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>