PIbd-11 Tarasov V.D. LabWork 7 Simple #7
@ -1,13 +1,20 @@
|
||||
using ProjectMonorail.Scripts.Monorail.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectMonorail.Scripts.Exceptions;
|
||||
using ProjectMonorail.Scripts.Monorail.CollectionGenericObjects;
|
||||
using ProjectMonorail.Scripts.Monorail.Drawnings;
|
||||
|
||||
namespace ProjectMonorail
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// Форма работы с компанией и ее коллекцией
|
||||
/// </summary>
|
||||
public partial class FormMonorailCollection : Form
|
||||
{
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Хранилище коллекций
|
||||
/// </summary>
|
||||
@ -21,10 +28,12 @@ namespace ProjectMonorail
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormMonorailCollection()
|
||||
public FormMonorailCollection(ILogger<FormMonorailCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new StorageCollection<DrawingMonorail>();
|
||||
_logger = logger;
|
||||
_logger.LogInformation("Форма загрузилась");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -51,35 +60,45 @@ namespace ProjectMonorail
|
||||
|
||||
private void SetMonorail(DrawingMonorail monorail)
|
||||
{
|
||||
if (monorail == null || _company == null) return;
|
||||
|
||||
if (_company + monorail != -1)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
if (monorail == null || _company == null) return;
|
||||
|
||||
if (_company + monorail != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Объект добавлен");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
LogException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void buttonRemoveMonorail_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) return;
|
||||
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
|
||||
|
||||
int position = Convert.ToInt32(maskedTextBox.Text);
|
||||
|
||||
if (_company - position != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) throw new Exception("Входные дынне пустые");
|
||||
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
|
||||
|
||||
int position = Convert.ToInt32(maskedTextBox.Text);
|
||||
|
||||
if (_company - position != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Объект удален");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch(Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
LogException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
@ -133,23 +152,30 @@ namespace ProjectMonorail
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
throw new Exception("Не все данные заполнены");
|
||||
}
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
}
|
||||
else if (radioButtonList.Checked)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
catch (Exception ex)
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
LogException(ex);
|
||||
}
|
||||
else if (radioButtonList.Checked)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text,
|
||||
collectionType);
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -159,18 +185,26 @@ namespace ProjectMonorail
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionDelete_Click(object sender, EventArgs e)
|
||||
{
|
||||
// TODO прописать логику удаления элемента из коллекции
|
||||
// нужно убедиться, что есть выбранная коллекция
|
||||
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
|
||||
// удалить и обновить ListBox
|
||||
if (listBoxCollection.SelectedItem == null || listBoxCollection.SelectedIndex < 0)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Коллекция для удаления не выбрана");
|
||||
return;
|
||||
// TODO прописать логику удаления элемента из коллекции
|
||||
// нужно убедиться, что есть выбранная коллекция
|
||||
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
|
||||
// удалить и обновить ListBox
|
||||
if (listBoxCollection.SelectedItem == null || listBoxCollection.SelectedIndex < 0)
|
||||
{
|
||||
MessageBox.Show("Коллекция для удаления не выбрана");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
_logger.LogInformation("Коллекция с название: " + listBoxCollection.SelectedItem.ToString() + " удалена");
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogException(ex);
|
||||
}
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -180,27 +214,33 @@ namespace ProjectMonorail
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCreateCompany_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
throw new Exception("Коллекция не выбрана");
|
||||
}
|
||||
ICollectionGenericObjects<DrawingMonorail>? collection =
|
||||
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
throw new Exception("Коллекция не проинициализирована");
|
||||
}
|
||||
switch (comboBoxSelectorCompany.Text)
|
||||
{
|
||||
case "Хранилище":
|
||||
_company = new DepotSharingService(pictureBox.Width, pictureBox.Height, collection);
|
||||
break;
|
||||
}
|
||||
panelCompanyTools.Enabled = true;
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
ICollectionGenericObjects<DrawingMonorail>? collection =
|
||||
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
if (collection == null)
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
return;
|
||||
LogException(ex);
|
||||
}
|
||||
switch (comboBoxSelectorCompany.Text)
|
||||
{
|
||||
case "Хранилище":
|
||||
_company = new DepotSharingService(pictureBox.Width,
|
||||
pictureBox.Height, collection);
|
||||
break;
|
||||
}
|
||||
panelCompanyTools.Enabled = true;
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -210,16 +250,19 @@ namespace ProjectMonorail
|
||||
/// <param name="e"></param>
|
||||
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
try
|
||||
{
|
||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Сохранение прошло успешно в файл {filename}", saveFileDialog.FileName);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
LogException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
@ -230,17 +273,48 @@ namespace ProjectMonorail
|
||||
/// <param name="e"></param>
|
||||
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
try
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Загрузка успешна завершена");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
LogException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void LogException(Exception ex)
|
||||
{
|
||||
if (ex is CollectionOverflowException)
|
||||
{
|
||||
_logger.LogError("Ошибка {Message}", ((CollectionOverflowException)ex).Message);
|
||||
}
|
||||
else if (ex is FileEmptyException)
|
||||
{
|
||||
_logger.LogError("Ошибка {Message}", ((FileEmptyException)ex).Message);
|
||||
}
|
||||
else if (ex is FileDoesNotExistException)
|
||||
{
|
||||
_logger.LogError("Ошибка {Message}", ((FileDoesNotExistException)ex).Message);
|
||||
}
|
||||
else if (ex is ObjectNotFoundException)
|
||||
{
|
||||
_logger.LogError("Ошибка {Message}", ((ObjectNotFoundException)ex).Message);
|
||||
}
|
||||
else if (ex is PositionOutOfCollectionException)
|
||||
{
|
||||
_logger.LogError("Ошибка {Message}", ((PositionOutOfCollectionException)ex).Message);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogError("Ошибка {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NLog.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectMonorail
|
||||
{
|
||||
internal static class Program
|
||||
@ -6,12 +11,28 @@ namespace ProjectMonorail
|
||||
/// The main entry point for the application.
|
||||
/// </summary>
|
||||
[STAThread]
|
||||
static void Main()
|
||||
private 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 FormMonorailCollection());
|
||||
|
||||
ServiceCollection services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
Application.Run(serviceProvider.GetRequiredService<FormMonorailCollection>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Êîíôèãóðàöèÿ ñåðâèñà DI
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormMonorailCollection>()
|
||||
.AddLogging(option => option.AddSerilog(dispose: true));
|
||||
|
||||
Log.Logger = new LoggerConfiguration()
|
||||
.MinimumLevel.Debug().WriteTo.File("C:\\Ó÷åáà\\PIbd-11_Tarasov_V.D._Simple\\ProjectMonorail\\log.txt").CreateLogger();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
@ -6,6 +6,13 @@
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
@ -0,0 +1,17 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectMonorail.Scripts.Exceptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку переполнения коллекции
|
||||
/// </summary>
|
||||
[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) { }
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectMonorail.Scripts.Exceptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что файл пустой
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class FileDoesNotExistException : ApplicationException
|
||||
{
|
||||
public FileDoesNotExistException() : base() { }
|
||||
public FileDoesNotExistException(string message) : base(message) { }
|
||||
public FileDoesNotExistException(string message, Exception exception) : base(message, exception) { }
|
||||
protected FileDoesNotExistException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
16
ProjectMonorail/Scripts/Exceptions/FileEmptyException.cs
Normal file
16
ProjectMonorail/Scripts/Exceptions/FileEmptyException.cs
Normal file
@ -0,0 +1,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectMonorail.Scripts.Exceptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class FileEmptyException : ApplicationException
|
||||
{
|
||||
public FileEmptyException() : base() { }
|
||||
public FileEmptyException(string message) : base(message) { }
|
||||
public FileEmptyException(string message, Exception exception) : base(message, exception) { }
|
||||
protected FileEmptyException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectMonorail.Scripts.Exceptions
|
||||
{
|
||||
/// <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) { }
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectMonorail.Scripts.Exceptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку выхода за границы коллекции
|
||||
/// </summary>
|
||||
[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) { }
|
||||
}
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
using ProjectMonorail.Scripts.Monorail.Drawnings;
|
||||
using ProjectMonorail.Scripts.Exceptions;
|
||||
using ProjectMonorail.Scripts.Monorail.Drawnings;
|
||||
|
||||
namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
{
|
||||
@ -35,7 +36,8 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
//private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
private int GetMaxCount => 40;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@ -59,7 +61,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company, DrawingMonorail monorail)
|
||||
{
|
||||
return company._collection?.Insert(monorail) ?? -1;
|
||||
return company._collection?.Insert(monorail) ?? throw new PositionOutOfCollectionException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -70,7 +72,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
/// <returns></returns>
|
||||
public static DrawingMonorail operator -(AbstractCompany company, int position)
|
||||
{
|
||||
return company._collection?.Remove(position);
|
||||
return company._collection?.Remove(position) ?? throw new ObjectNotFoundException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -1,4 +1,6 @@
|
||||
|
||||
using ProjectMonorail.Scripts.Exceptions;
|
||||
|
||||
namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
{
|
||||
/// <summary>
|
||||
@ -38,7 +40,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
public T? Get(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position < 0 || position >= _collection.Count) return null;
|
||||
if (position < 0 || position >= _collection.Count) throw new PositionOutOfCollectionException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
@ -47,7 +49,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO вставка в конец набора
|
||||
|
||||
if (_collection.Count + 1 > _maxCount) return -1;
|
||||
if (_collection.Count + 1 > _maxCount) throw new CollectionOverflowException(_maxCount);
|
||||
|
||||
_collection.Add(obj);
|
||||
return _collection.Count + 1;
|
||||
@ -58,7 +60,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO проверка позиции
|
||||
// TODO вставка по позиции
|
||||
if (position < 0 || position > _collection.Count || _collection[position] != null) return -1;
|
||||
if (position < 0 || position > _collection.Count || _collection[position] != null) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
_collection.Insert(position, obj);
|
||||
|
||||
@ -70,7 +72,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из списка
|
||||
|
||||
if (position < 0 || position > _collection.Count) return null;
|
||||
if (position < 0 || position > _collection.Count) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
T temp = _collection[position];
|
||||
|
||||
|
@ -1,5 +1,4 @@
|
||||
using ProjectMonorail.Scripts.Monorail.Drawnings;
|
||||
using System.Diagnostics;
|
||||
using ProjectMonorail.Scripts.Exceptions;
|
||||
|
||||
namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
{
|
||||
@ -61,7 +60,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
if (InsertingElementCollection(i, obj)) return i;
|
||||
}
|
||||
|
||||
return -1;
|
||||
throw new CollectionOverflowException("Превышение лимита Count");
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
@ -71,7 +70,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
// ищется свободное место после этой позиции и идет вставка туда
|
||||
// если нет после, ищем до
|
||||
// TODO вставка
|
||||
if (!(position >= 0 && position < Count)) return -1;
|
||||
if (!(position >= 0 && position < Count)) throw new PositionOutOfCollectionException(position);
|
||||
if (InsertingElementCollection(position, obj)) return position;
|
||||
|
||||
for (int i = position + 1; i < Count; i++)
|
||||
@ -84,7 +83,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
if (InsertingElementCollection(i, obj)) return i;
|
||||
}
|
||||
|
||||
return -1;
|
||||
throw new CollectionOverflowException("Нет свободного места для вставки");
|
||||
}
|
||||
|
||||
public T Remove(int position)
|
||||
@ -92,7 +91,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из массива, присвоив элементу массива значение null
|
||||
|
||||
if (!(position >= 0 && position < Count) || _collection[position] == null) return null;
|
||||
if (!(position >= 0 && position < Count) || _collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
|
||||
T obj = _collection[position];
|
||||
_collection[position] = null;
|
||||
|
@ -105,48 +105,49 @@ namespace ProjectMonorail.Scripts.Monorail.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("Storage is empty");
|
||||
eegov
commented
Требовалось заменить класс Exception на его более подходящих наследников Требовалось заменить класс Exception на его более подходящих наследников
|
||||
}
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
StringBuilder sb = new();
|
||||
sb.Append(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in
|
||||
_storages)
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
{
|
||||
sb.Append(Environment.NewLine);
|
||||
// не сохраняем пустые коллекции
|
||||
if (value.Value.Count == 0)
|
||||
writer.Write(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
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))
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
stringBuilder.Append(Environment.NewLine);
|
||||
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sb.Append(data);
|
||||
sb.Append(_separatorItems);
|
||||
|
||||
stringBuilder.Append(value.Key);
|
||||
stringBuilder.Append(_separatorForKeyValue);
|
||||
stringBuilder.Append(value.Value.GetCollectionType);
|
||||
stringBuilder.Append(_separatorForKeyValue);
|
||||
stringBuilder.Append(value.Value.MaxCount);
|
||||
stringBuilder.Append(_separatorForKeyValue);
|
||||
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
if (string.IsNullOrEmpty(data))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
stringBuilder.Append(data);
|
||||
stringBuilder.Append(_separatorItems);
|
||||
}
|
||||
writer.Write(stringBuilder);
|
||||
}
|
||||
}
|
||||
using FileStream fs = new(filename, FileMode.Create);
|
||||
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
|
||||
fs.Write(info, 0, info.Length);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -154,67 +155,57 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
/// </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;
|
||||
}
|
||||
string bufferTextFromFile = "";
|
||||
using (FileStream fs = new(filename, FileMode.Open))
|
||||
{
|
||||
byte[] b = new byte[fs.Length];
|
||||
UTF8Encoding temp = new(true);
|
||||
while (fs.Read(b, 0, b.Length) > 0)
|
||||
{
|
||||
bufferTextFromFile += temp.GetString(b);
|
||||
}
|
||||
}
|
||||
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (strs == null || strs.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exceptions.FileDoesNotExistException("Файл не существует " + filename);
|
||||
}
|
||||
|
||||
if (!strs[0].Equals(_collectionKey))
|
||||
using (StreamReader streamRader = File.OpenText(filename))
|
||||
{
|
||||
//если нет такой записи, то это не те данные
|
||||
return false;
|
||||
}
|
||||
string inputString = streamRader.ReadLine();
|
||||
|
||||
_storages.Clear();
|
||||
foreach (string data in strs)
|
||||
{
|
||||
string[] record = data.Split(_separatorForKeyValue,
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
if (inputString == null || inputString.Length == 0)
|
||||
{
|
||||
continue;
|
||||
throw new Exceptions.FileEmptyException("Файл пустой " + filename);
|
||||
}
|
||||
CollectionType collectionType =
|
||||
(CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection =
|
||||
StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
|
||||
if (!inputString.StartsWith(_collectionKey))
|
||||
{
|
||||
return false;
|
||||
throw new Exceptions.ObjectNotFoundException();
|
||||
}
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
string[] set = record[3].Split(_separatorItems,
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
|
||||
_storages.Clear();
|
||||
string strs = "";
|
||||
while ((strs = streamRader.ReadLine()) != null)
|
||||
{
|
||||
if (elem?.CreateDrawingMonorail() is T monorail)
|
||||
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
{
|
||||
if (collection.Insert(monorail) == -1)
|
||||
continue;
|
||||
}
|
||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
throw new Exceptions.ObjectNotFoundException();
|
||||
}
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawingMonorail() is T ship)
|
||||
{
|
||||
return false;
|
||||
if (collection.Insert(ship) == -1)
|
||||
{
|
||||
throw new Exceptions.PositionOutOfCollectionException();
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
@ -226,5 +217,17 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
public T? this[int index]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (index >= 0 && index < Keys.Count && Keys[index] != null)
|
||||
{
|
||||
return (T)_storages[Keys[index]];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
14
ProjectMonorail/log.txt
Normal file
14
ProjectMonorail/log.txt
Normal file
@ -0,0 +1,14 @@
|
||||
2024-05-06 13:58:46.635 +04:00 [INF] Форма загрузилась
|
||||
2024-05-06 13:58:52.710 +04:00 [INF] Загрузка успешна завершена
|
||||
2024-05-06 13:58:54.975 +04:00 [ERR] Ошибка Коллекция не выбрана
|
||||
2024-05-06 14:05:27.673 +04:00 [INF] Форма загрузилась
|
||||
2024-05-06 14:05:33.453 +04:00 [INF] Загрузка успешна завершена
|
||||
2024-05-06 14:05:45.167 +04:00 [ERR] Ошибка Превышение лимита Count
|
||||
2024-05-06 14:05:55.335 +04:00 [INF] Объект удален
|
||||
2024-05-06 14:05:57.340 +04:00 [ERR] Ошибка Не найден объект по позиции 1
|
||||
2024-05-06 14:05:59.747 +04:00 [ERR] Ошибка Не найден объект по позиции 1
|
||||
2024-05-06 14:07:02.813 +04:00 [INF] Форма загрузилась
|
||||
2024-05-06 14:07:56.306 +04:00 [INF] Загрузка успешна завершена
|
||||
2024-05-06 14:08:05.188 +04:00 [ERR] Ошибка Превышение лимита Count
|
||||
2024-05-06 14:08:10.722 +04:00 [INF] Объект удален
|
||||
2024-05-06 14:08:14.155 +04:00 [ERR] Ошибка Не найден объект по позиции 1
|
Loading…
x
Reference in New Issue
Block a user
Настройку логера следует выносить в отдельный конфигурационный файл, чтобы ее можно было менять без пересборки проекта