Not Done
This commit is contained in:
parent
e1cc1e40ad
commit
5c91dc45fd
13
ProjectMonorail/Configs/nlog.config
Normal file
13
ProjectMonorail/Configs/nlog.config
Normal 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="carlog-${shortdate}.log" />
|
||||||
|
</targets>
|
||||||
|
<rules>
|
||||||
|
<logger name="*" minlevel="Debug" writeTo="tofile" />
|
||||||
|
</rules>
|
||||||
|
</nlog>
|
||||||
|
</configuration>
|
@ -1,13 +1,19 @@
|
|||||||
using ProjectMonorail.Scripts.Monorail.CollectionGenericObjects;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using ProjectMonorail.Scripts.Monorail.CollectionGenericObjects;
|
||||||
using ProjectMonorail.Scripts.Monorail.Drawnings;
|
using ProjectMonorail.Scripts.Monorail.Drawnings;
|
||||||
|
|
||||||
namespace ProjectMonorail
|
namespace ProjectMonorail
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
///
|
/// Форма работы с компанией и ее коллекцией
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public partial class FormMonorailCollection : Form
|
public partial class FormMonorailCollection : Form
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Логер
|
||||||
|
/// </summary>
|
||||||
|
private readonly ILogger _logger;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Хранилище коллекций
|
/// Хранилище коллекций
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@ -21,10 +27,11 @@ namespace ProjectMonorail
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Конструктор
|
/// Конструктор
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public FormMonorailCollection()
|
public FormMonorailCollection(ILogger<FormMonorailCollection> logger)
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
_storageCollection = new StorageCollection<DrawingMonorail>();
|
_storageCollection = new StorageCollection<DrawingMonorail>();
|
||||||
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -50,6 +57,8 @@ namespace ProjectMonorail
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void SetMonorail(DrawingMonorail monorail)
|
private void SetMonorail(DrawingMonorail monorail)
|
||||||
|
{
|
||||||
|
try
|
||||||
{
|
{
|
||||||
if (monorail == null || _company == null) return;
|
if (monorail == null || _company == null) return;
|
||||||
|
|
||||||
@ -58,15 +67,19 @@ namespace ProjectMonorail
|
|||||||
MessageBox.Show("Объект добавлен");
|
MessageBox.Show("Объект добавлен");
|
||||||
pictureBox.Image = _company.Show();
|
pictureBox.Image = _company.Show();
|
||||||
}
|
}
|
||||||
else
|
}
|
||||||
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось добавить объект");
|
MessageBox.Show("Не удалось добавить объект");
|
||||||
|
_logger.LogError("Ошибка {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void buttonRemoveMonorail_Click(object sender, EventArgs e)
|
private void buttonRemoveMonorail_Click(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) return;
|
try
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) throw new Exception("Входные дынне пустые");
|
||||||
|
|
||||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
|
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
|
||||||
|
|
||||||
@ -77,9 +90,11 @@ namespace ProjectMonorail
|
|||||||
MessageBox.Show("Объект удален");
|
MessageBox.Show("Объект удален");
|
||||||
pictureBox.Image = _company.Show();
|
pictureBox.Image = _company.Show();
|
||||||
}
|
}
|
||||||
else
|
}
|
||||||
|
catch(Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось удалить объект");
|
MessageBox.Show("Не удалось удалить объект");
|
||||||
|
_logger.LogError("Ошибка {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -132,6 +147,8 @@ namespace ProjectMonorail
|
|||||||
/// <param name="sender"></param>
|
/// <param name="sender"></param>
|
||||||
/// <param name="e"></param>
|
/// <param name="e"></param>
|
||||||
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
|
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
|
||||||
|
{
|
||||||
|
try
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||||
{
|
{
|
||||||
@ -151,6 +168,11 @@ namespace ProjectMonorail
|
|||||||
collectionType);
|
collectionType);
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
}
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError("Ошибка {Message}", ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Удаление коллекции
|
/// Удаление коллекции
|
||||||
@ -159,6 +181,7 @@ namespace ProjectMonorail
|
|||||||
/// <param name="e"></param>
|
/// <param name="e"></param>
|
||||||
private void ButtonCollectionDelete_Click(object sender, EventArgs e)
|
private void ButtonCollectionDelete_Click(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
// TODO прописать логику удаления элемента из коллекции
|
// TODO прописать логику удаления элемента из коллекции
|
||||||
// нужно убедиться, что есть выбранная коллекция
|
// нужно убедиться, что есть выбранная коллекция
|
||||||
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
|
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
|
||||||
@ -172,6 +195,11 @@ namespace ProjectMonorail
|
|||||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
}
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError("Ошибка {Message}", ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Создание компании
|
/// Создание компании
|
||||||
@ -179,6 +207,8 @@ namespace ProjectMonorail
|
|||||||
/// <param name="sender"></param>
|
/// <param name="sender"></param>
|
||||||
/// <param name="e"></param>
|
/// <param name="e"></param>
|
||||||
private void ButtonCreateCompany_Click(object sender, EventArgs e)
|
private void ButtonCreateCompany_Click(object sender, EventArgs e)
|
||||||
|
{
|
||||||
|
try
|
||||||
{
|
{
|
||||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||||
{
|
{
|
||||||
@ -195,13 +225,17 @@ namespace ProjectMonorail
|
|||||||
switch (comboBoxSelectorCompany.Text)
|
switch (comboBoxSelectorCompany.Text)
|
||||||
{
|
{
|
||||||
case "Хранилище":
|
case "Хранилище":
|
||||||
_company = new DepotSharingService(pictureBox.Width,
|
_company = new DepotSharingService(pictureBox.Width, pictureBox.Height, collection);
|
||||||
pictureBox.Height, collection);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
panelCompanyTools.Enabled = true;
|
panelCompanyTools.Enabled = true;
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
}
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError("Ошибка {Message}", ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Обработка нажатия "Сохранения"
|
/// Обработка нажатия "Сохранения"
|
||||||
@ -209,17 +243,20 @@ namespace ProjectMonorail
|
|||||||
/// <param name="sender"></param>
|
/// <param name="sender"></param>
|
||||||
/// <param name="e"></param>
|
/// <param name="e"></param>
|
||||||
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
|
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
|
||||||
|
{
|
||||||
|
try
|
||||||
{
|
{
|
||||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||||
{
|
{
|
||||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||||
{
|
|
||||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||||
|
_logger.LogInformation("Сохранение прошло успешно в файл {filename}", saveFileDialog.FileName);
|
||||||
}
|
}
|
||||||
else
|
}
|
||||||
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
}
|
_logger.LogError("Ошибка {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -229,18 +266,21 @@ namespace ProjectMonorail
|
|||||||
/// <param name="sender"></param>
|
/// <param name="sender"></param>
|
||||||
/// <param name="e"></param>
|
/// <param name="e"></param>
|
||||||
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
|
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
|
||||||
|
{
|
||||||
|
try
|
||||||
{
|
{
|
||||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||||
{
|
{
|
||||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
_storageCollection.LoadData(openFileDialog.FileName);
|
||||||
{
|
|
||||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
|
_logger.LogInformation("Загрузка успешна завершена");
|
||||||
}
|
}
|
||||||
else
|
}
|
||||||
|
catch(Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
}
|
_logger.LogError("Ошибка {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,7 @@
|
|||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NLog.Extensions.Logging;
|
||||||
|
|
||||||
namespace ProjectMonorail
|
namespace ProjectMonorail
|
||||||
{
|
{
|
||||||
internal static class Program
|
internal static class Program
|
||||||
@ -6,12 +10,29 @@ namespace ProjectMonorail
|
|||||||
/// The main entry point for the application.
|
/// The main entry point for the application.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[STAThread]
|
[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();
|
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.SetMinimumLevel(LogLevel.Information);
|
||||||
|
option.AddNLog("nlog.config");
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -6,6 +6,10 @@
|
|||||||
<UseWindowsForms>true</UseWindowsForms>
|
<UseWindowsForms>true</UseWindowsForms>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
|
||||||
|
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
|
||||||
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Compile Update="Properties\Resources.Designer.cs">
|
<Compile Update="Properties\Resources.Designer.cs">
|
||||||
<DesignTime>True</DesignTime>
|
<DesignTime>True</DesignTime>
|
||||||
@ -19,4 +23,9 @@
|
|||||||
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
||||||
</EmbeddedResource>
|
</EmbeddedResource>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<None Update="Configs\nlog.config">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
@ -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,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
|
namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||||
{
|
{
|
||||||
@ -59,7 +60,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static int operator +(AbstractCompany company, DrawingMonorail monorail)
|
public static int operator +(AbstractCompany company, DrawingMonorail monorail)
|
||||||
{
|
{
|
||||||
return company._collection?.Insert(monorail) ?? -1;
|
return company._collection?.Insert(monorail) ?? throw new PositionOutOfCollectionException();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -70,7 +71,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static DrawingMonorail operator -(AbstractCompany company, int position)
|
public static DrawingMonorail operator -(AbstractCompany company, int position)
|
||||||
{
|
{
|
||||||
return company._collection?.Remove(position);
|
return company._collection?.Remove(position) ?? throw new ObjectNotFoundException();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
|
|
||||||
|
using ProjectMonorail.Scripts.Exceptions;
|
||||||
|
|
||||||
namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -38,7 +40,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
public T? Get(int position)
|
public T? Get(int position)
|
||||||
{
|
{
|
||||||
// TODO проверка позиции
|
// TODO проверка позиции
|
||||||
if (position < 0 || position >= _collection.Count) return null;
|
if (position < 0 || position >= _collection.Count) throw new PositionOutOfCollectionException(position);
|
||||||
return _collection[position];
|
return _collection[position];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -47,7 +49,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
// TODO проверка, что не превышено максимальное количество элементов
|
// TODO проверка, что не превышено максимальное количество элементов
|
||||||
// TODO вставка в конец набора
|
// TODO вставка в конец набора
|
||||||
|
|
||||||
if (_collection.Count + 1 > _maxCount) return -1;
|
if (_collection.Count + 1 > _maxCount) throw new CollectionOverflowException(_maxCount);
|
||||||
|
|
||||||
_collection.Add(obj);
|
_collection.Add(obj);
|
||||||
return _collection.Count + 1;
|
return _collection.Count + 1;
|
||||||
@ -58,7 +60,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
// TODO проверка, что не превышено максимальное количество элементов
|
// TODO проверка, что не превышено максимальное количество элементов
|
||||||
// TODO проверка позиции
|
// 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);
|
_collection.Insert(position, obj);
|
||||||
|
|
||||||
@ -70,7 +72,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
// TODO проверка позиции
|
// TODO проверка позиции
|
||||||
// TODO удаление объекта из списка
|
// TODO удаление объекта из списка
|
||||||
|
|
||||||
if (position < 0 || position > _collection.Count) return null;
|
if (position < 0 || position > _collection.Count) throw new PositionOutOfCollectionException(position);
|
||||||
|
|
||||||
T temp = _collection[position];
|
T temp = _collection[position];
|
||||||
|
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
using ProjectMonorail.Scripts.Monorail.Drawnings;
|
using ProjectMonorail.Scripts.Exceptions;
|
||||||
using System.Diagnostics;
|
|
||||||
|
|
||||||
namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
||||||
{
|
{
|
||||||
@ -61,7 +60,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
if (InsertingElementCollection(i, obj)) return i;
|
if (InsertingElementCollection(i, obj)) return i;
|
||||||
}
|
}
|
||||||
|
|
||||||
return -1;
|
throw new Exception("Превышение лимита Count");
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj, int position)
|
public int Insert(T obj, int position)
|
||||||
@ -71,7 +70,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
// ищется свободное место после этой позиции и идет вставка туда
|
// ищется свободное место после этой позиции и идет вставка туда
|
||||||
// если нет после, ищем до
|
// если нет после, ищем до
|
||||||
// TODO вставка
|
// TODO вставка
|
||||||
if (!(position >= 0 && position < Count)) return -1;
|
if (!(position >= 0 && position < Count)) throw new PositionOutOfCollectionException(position);
|
||||||
if (InsertingElementCollection(position, obj)) return position;
|
if (InsertingElementCollection(position, obj)) return position;
|
||||||
|
|
||||||
for (int i = position + 1; i < Count; i++)
|
for (int i = position + 1; i < Count; i++)
|
||||||
@ -84,7 +83,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
if (InsertingElementCollection(i, obj)) return i;
|
if (InsertingElementCollection(i, obj)) return i;
|
||||||
}
|
}
|
||||||
|
|
||||||
return -1;
|
throw new Exception("Нет свободного места для вставки");
|
||||||
}
|
}
|
||||||
|
|
||||||
public T Remove(int position)
|
public T Remove(int position)
|
||||||
@ -92,7 +91,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
// TODO проверка позиции
|
// TODO проверка позиции
|
||||||
// TODO удаление объекта из массива, присвоив элементу массива значение null
|
// TODO удаление объекта из массива, присвоив элементу массива значение null
|
||||||
|
|
||||||
if (!(position >= 0 && position < Count) || _collection[position] == null) return null;
|
if (!(position >= 0 && position < Count) || _collection[position] == null) throw new PositionOutOfCollectionException(position);
|
||||||
|
|
||||||
T obj = _collection[position];
|
T obj = _collection[position];
|
||||||
_collection[position] = null;
|
_collection[position] = null;
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
using ProjectMonorail.Scripts.Monorail.Drawnings;
|
using ProjectMonorail.Scripts.Exceptions;
|
||||||
|
using ProjectMonorail.Scripts.Monorail.Drawnings;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
@ -66,7 +67,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
collection = new MassiveGenericObjects<T>();
|
collection = new MassiveGenericObjects<T>();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
return;
|
throw new Exception("Collection Type is not selected: collectionType = " + collectionType);
|
||||||
}
|
}
|
||||||
|
|
||||||
_storages.Add(name, collection);
|
_storages.Add(name, collection);
|
||||||
@ -105,12 +106,13 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
/// </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))
|
||||||
{
|
{
|
||||||
File.Delete(filename);
|
File.Delete(filename);
|
||||||
@ -146,7 +148,6 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
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>
|
||||||
@ -154,12 +155,13 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
/// </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 Exception("Файл не существует");
|
||||||
}
|
}
|
||||||
|
|
||||||
string bufferTextFromFile = "";
|
string bufferTextFromFile = "";
|
||||||
using (FileStream fs = new(filename, FileMode.Open))
|
using (FileStream fs = new(filename, FileMode.Open))
|
||||||
{
|
{
|
||||||
@ -173,13 +175,12 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
|
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, 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();
|
||||||
@ -197,7 +198,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
StorageCollection<T>.CreateCollection(collectionType);
|
StorageCollection<T>.CreateCollection(collectionType);
|
||||||
if (collection == null)
|
if (collection == null)
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("Не удалось определить тип коллекции: " + record[1]);
|
||||||
}
|
}
|
||||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||||
string[] set = record[3].Split(_separatorItems,
|
string[] set = record[3].Split(_separatorItems,
|
||||||
@ -206,15 +207,18 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
|
|||||||
{
|
{
|
||||||
if (elem?.CreateDrawingMonorail() is T monorail)
|
if (elem?.CreateDrawingMonorail() is T monorail)
|
||||||
{
|
{
|
||||||
if (collection.Insert(monorail) == -1)
|
try
|
||||||
{
|
{
|
||||||
return false;
|
if (collection.Insert(monorail) == -1)
|
||||||
|
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||||
|
}
|
||||||
|
catch (CollectionOverflowException ex) {
|
||||||
|
throw new Exception("Коллекция переполнена", ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_storages.Add(record[0], collection);
|
_storages.Add(record[0], collection);
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||||
|
Loading…
Reference in New Issue
Block a user