This commit is contained in:
zw1st 2024-06-10 10:11:49 +04:00
parent ac11b4d69d
commit ce84c8d6be
11 changed files with 241 additions and 105 deletions

View File

@ -1,4 +1,5 @@
using Cruiser.Drawings; using Cruiser.Drawings;
using Cruiser.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -37,7 +38,7 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, которое можно разместить в окне /// Вычисление максимального количества элементов, которое можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeHeight * _placeSizeWidth); private int GetMaxCount => (_pictureWidth - 70) * ((_pictureHeight - 20) / 2) / (_placeSizeHeight * _placeSizeWidth);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -95,9 +96,15 @@ public abstract class AbstractCompany
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{ {
try {
DrawingShip? obj = _collection?.Get(i); DrawingShip? obj = _collection?.Get(i);
obj?.DrawTransport(g); obj?.DrawTransport(g);
} }
catch (ObjectNotFoundException)
{
}
}
return bitmap; return bitmap;
} }

View File

@ -1,4 +1,5 @@
using Cruiser.Drawings; using Cruiser.Drawings;
using Cruiser.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -34,15 +35,20 @@ public class Docs : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{ {
if (nowHeight > _pictureHeight) if (nowHeight > (_pictureHeight / _placeSizeHeight) * _placeSizeHeight)
{ {
return; return;
} }
try
{
if (_collection?.Get(i) != null) if (_collection?.Get(i) != null)
{ {
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(nowWidth, nowHeight); _collection?.Get(i)?.SetPosition(nowWidth, nowHeight);
} }
}
catch (ObjectNotFoundException) {
}
if (nowWidth < _pictureWidth - _placeSizeWidth - 35) nowWidth += _placeSizeWidth; if (nowWidth < _pictureWidth - _placeSizeWidth - 35) nowWidth += _placeSizeWidth;
else else

View File

@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Cruiser.Exceptions;
namespace Cruiser.CollectionGenericObjects; namespace Cruiser.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T> public class ListGenericObjects<T> : ICollectionGenericObjects<T>
@ -49,40 +49,28 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= Count) if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
{
return null;
}
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
if (Count == _maxCount) if (Count == _maxCount) throw new CollectionOverflowException();
{
return -1;
}
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (Count == _maxCount) if (Count == _maxCount) throw new CollectionOverflowException();
{ if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
return -1;
}
if (position >= Count || position < 0)
{
return -1;
}
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
public T Remove(int position) public T Remove(int position)
{ {
if (position >= Count || position < 0) return null; if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
T temp = _collection[position]; T temp = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return temp; return temp;

View File

@ -4,7 +4,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Cruiser.Exceptions;
namespace Cruiser.CollectionGenericObjects; namespace Cruiser.CollectionGenericObjects;
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T> public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
@ -46,12 +46,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position >= 0 || position < Count) if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
{ if (_collection[position] == null) throw new ObjectNotFoundException();
return _collection[position]; return _collection[position];
} }
return null;
}
public int Insert(T obj) public int Insert(T obj)
{ {
@ -63,46 +61,47 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i; return i;
} }
} }
return -1; throw new CollectionOverflowException();
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position >= _collection.Length || position < 0) if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
if (_collection[position] == null)
{ {
return -1; _collection[position] = obj;
return position;
} }
if (_collection[position] != null) int temp = position + 1;
while (temp < Count)
{ {
return -1; if (_collection[temp] == null)
}
for (int i = position; i < _collection.Length; i++)
{ {
if (_collection[i] == null) _collection[temp] = obj;
return temp;
}
++temp;
}
temp = position - 1;
while (temp >= 0)
{ {
_collection[i] = obj; if (_collection[temp] == null)
return i;
}
}
for (int i = 0; i < position; i++)
{ {
_collection[i] = obj; _collection[temp] = obj;
return i; return temp;
} }
--temp;
return -1; }
throw new CollectionOverflowException();
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position > _collection.Length || position < 0) if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
{ T? myObject = _collection[position];
return null; if (myObject == null) throw new ObjectNotFoundException();
}
T? obj = _collection[position];
_collection[position] = null; _collection[position] = null;
return obj; return myObject;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()

View File

@ -1,10 +1,12 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Cruiser.Drawings; using Cruiser.Drawings;
using Cruiser.Entities; using Cruiser.Entities;
using Cruiser.Exceptions;
namespace Cruiser.CollectionGenericObjects; namespace Cruiser.CollectionGenericObjects;
public class StorageCollection<T> where T : DrawingShip public class StorageCollection<T> where T : DrawingShip
@ -48,11 +50,11 @@ public class StorageCollection<T> where T : DrawingShip
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -89,7 +91,6 @@ public class StorageCollection<T> where T : DrawingShip
using FileStream fs = new(filename, FileMode.Create); using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length); fs.Write(info, 0, info.Length);
return true;
} }
/// <summary> /// <summary>
@ -97,11 +98,11 @@ public class StorageCollection<T> where T : DrawingShip
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не существует");
} }
string bufferTextFromFile = ""; string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open)) using (FileStream fs = new(filename, FileMode.Open))
@ -117,12 +118,11 @@ public class StorageCollection<T> where T : DrawingShip
StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0) if (strs == null || strs.Length == 0)
{ {
return false; throw new Exception("В файле нет данных");
} }
if (!strs[0].Equals(_collectionKey)) if (!strs[0].Equals(_collectionKey))
{ {
//если нет такой записи, то это не те данные throw new Exception("В файле неверные данные");
return false;
} }
_storages.Clear(); _storages.Clear();
foreach (string data in strs) foreach (string data in strs)
@ -139,7 +139,7 @@ public class StorageCollection<T> where T : DrawingShip
StorageCollection<T>.CreateCollection(collectionType); StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new Exception("Не удалось создать коллекцию");
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, string[] set = record[3].Split(_separatorItems,
@ -147,16 +147,23 @@ public class StorageCollection<T> where T : DrawingShip
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawingShip() is T ship) if (elem?.CreateDrawingShip() is T ship)
{
try
{ {
if (collection.Insert(ship) == -1) if (collection.Insert(ship) == -1)
{ {
return false; throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new DataException("Коллекция переполнена", ex);
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
return true;
} }
/// <summary> /// <summary>

View File

@ -8,4 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" 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" Version="4.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.1.0-dev-00943" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.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) { }
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.Exceptions;
[Serializable]
internal class 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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.Exceptions;
[Serializable]
internal class 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

@ -1,5 +1,8 @@
using Cruiser.CollectionGenericObjects; using Cruiser.CollectionGenericObjects;
using Cruiser.Drawings; using Cruiser.Drawings;
using Cruiser.Exceptions;
using Microsoft.Extensions.Logging;
using System.Windows.Forms;
namespace Cruiser; namespace Cruiser;
@ -7,27 +10,34 @@ public partial class FormShipCollection : Form
{ {
private readonly StorageCollection<DrawingShip> _storageCollection; private readonly StorageCollection<DrawingShip> _storageCollection;
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
public FormShipCollection() private readonly ILogger _logger;
public FormShipCollection(ILogger<FormShipCollection> logger)
{ {
_storageCollection = new(); _storageCollection = new();
InitializeComponent(); InitializeComponent();
_logger = logger;
} }
private void SetShip(DrawingShip? ship) private void SetShip(DrawingShip? ship)
{
try
{ {
if (_company == null || ship == null) if (_company == null || ship == null)
{ {
return; return;
} }
if (_company + ship != -1) if (_company + ship != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _company.Show(); pictureBoxCollection.Image = _company.Show();
_logger.LogInformation("Добавлен объект: {0}", ship.GetDataForSave());
} }
else
}
catch (CollectionOverflowException)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: В коллекции превышено допустимое количество");
} }
} }
@ -55,23 +65,35 @@ public partial class FormShipCollection : Form
{ {
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBox.Text); int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos == 1) try
{
if (_company - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _company.Show(); pictureBoxCollection.Image = _company.Show();
_logger.LogInformation("Удалён объект по позиции {0}", pos);
} }
else else
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
} }
} }
catch (PositionOutOfCollectionException)
{
MessageBox.Show($"Ошибка при удалении по позиции {pos}");
_logger.LogError("Ошибка при удалении по позиции {0}", pos);
}
catch (ObjectNotFoundException)
{
MessageBox.Show($"Ошибка: Не найден объект по позиции {pos}");
_logger.LogError("Ошибка: Не найден объект по позиции {0}", pos);
}
}
private void ButtonGoToCheck_Click(object sender, EventArgs e) private void ButtonGoToCheck_Click(object sender, EventArgs e)
{ {
@ -79,28 +101,29 @@ public partial class FormShipCollection : Form
{ {
return; return;
} }
try
{
DrawingShip? ship = null; DrawingShip? ship = null;
int counter = 100; int counter = 100;
while (ship == null) while(ship == null)
{ {
ship = _company.GetRandomObject(); ship = _company.GetRandomObject();
counter--; counter--;
if (counter <= 100) if (counter <= 0) break;
{
break;
}
} }
if (ship == null) if (ship == null)
{ {
return; return;
} }
FormCruiser form = new FormCruiser();
FormCruiser form = new() form.SetShip = ship;
{
SetShip = ship
};
form.ShowDialog(); form.ShowDialog();
} }
catch (ObjectNotFoundException)
{
_logger.LogError("Ошибка при передаче на FormCruiser");
}
}
private void ButtonRefresh_Click(object sender, EventArgs e) private void ButtonRefresh_Click(object sender, EventArgs e)
{ {
@ -132,6 +155,7 @@ public partial class FormShipCollection : Form
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems(); RefreshListBoxItems();
_logger.LogInformation("Добавлена коллекция: {Collection} типа: {Type}", textBoxCollectionName.Text, collectionType);
} }
private void ButtonCollectionDel_Click(object sender, EventArgs e) private void ButtonCollectionDel_Click(object sender, EventArgs e)
@ -149,6 +173,7 @@ public partial class FormShipCollection : Form
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems(); RefreshListBoxItems();
_logger.LogInformation("Коллекция удалена: {0}", textBoxCollectionName.Text);
} }
private void RefreshListBoxItems() private void RefreshListBoxItems()
{ {
@ -182,6 +207,8 @@ public partial class FormShipCollection : Form
{ {
case "Хранилище": case "Хранилище":
_company = new Docs(pictureBoxCollection.Width, pictureBoxCollection.Height, collection); _company = new Docs(pictureBoxCollection.Width, pictureBoxCollection.Height, collection);
_logger.LogInformation("Создна компания типа {Company}, коллекция: {Collection}", comboBoxSelectorCompany.Text, textBoxCollectionName.Text);
_logger.LogInformation("Создана компания на коллекции: {Collection}", textBoxCollectionName.Text);
break; break;
} }
@ -193,15 +220,18 @@ public partial class FormShipCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл {filename}", saveFileDialog.FileName);
} }
else catch(Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show(ex.Message, "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
@ -210,16 +240,23 @@ public partial class FormShipCollection : Form
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{ {
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach (var collection in _storageCollection.Keys)
{
listBoxCollection.Items.Add(collection);
}
_logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
RefreshListBoxItems(); RefreshListBoxItems();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось сохранить", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
} }

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Cruiser namespace Cruiser
{ {
internal static class Program internal static class Program
@ -11,7 +16,27 @@ namespace Cruiser
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormShipCollection()); ServiceCollection services = new();
ConfigureService(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormShipCollection>());
}
private static void ConfigureService(ServiceCollection services)
{
services
.AddSingleton<FormShipCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
var config = new ConfigurationBuilder()
.AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
option.AddSerilog(Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger());
});
} }
} }
} }