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

View File

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

View File

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

View File

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

View File

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

View File

@ -8,4 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings>
</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>

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