LabWork07
This commit is contained in:
parent
058d31a0f7
commit
83c9dfd598
@ -1,4 +1,5 @@
|
|||||||
using System;
|
using ProjectMotorboat.Exceptions;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
@ -49,39 +50,36 @@ where T : class
|
|||||||
|
|
||||||
public T? Get(int position)
|
public T? Get(int position)
|
||||||
{
|
{
|
||||||
// TODO проверка позиции
|
//TODO выброс ошибки если выход за границу
|
||||||
if (position >= Count || position < 0) return null;
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
return _collection[position];
|
return _collection[position];
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj)
|
public int Insert(T obj)
|
||||||
{
|
{
|
||||||
// TODO проверка, что не превышено максимальное количество элементов
|
|
||||||
// TODO вставка в конец набора
|
// TODO выброс ошибки если переполнение
|
||||||
if (Count + 1 > _maxCount) return -1;
|
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||||
_collection.Add(obj);
|
_collection.Add(obj);
|
||||||
return Count;
|
return Count;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj, int position)
|
public int Insert(T obj, int position)
|
||||||
{
|
{
|
||||||
// TODO проверка, что не превышено максимальное количество элементов
|
// TODO выброс ошибки если переполнение
|
||||||
// TODO проверка позиции
|
// TODO выброс ошибки если за границу
|
||||||
// TODO вставка по позиции
|
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||||
if (Count + 1 > _maxCount) return -1;
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
if (position < 0 || position > Count) return -1;
|
|
||||||
_collection.Insert(position, obj);
|
_collection.Insert(position, obj);
|
||||||
return 1;
|
return position;
|
||||||
}
|
}
|
||||||
|
|
||||||
public T? Remove(int position)
|
public T Remove(int position)
|
||||||
{
|
{
|
||||||
// TODO проверка позиции
|
// TODO если выброс за границу
|
||||||
// TODO удаление объекта из списка
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
if (position < 0 || position > Count) return null;
|
T obj = _collection[position];
|
||||||
T? pos = _collection[position];
|
|
||||||
_collection.RemoveAt(position);
|
_collection.RemoveAt(position);
|
||||||
return pos;
|
return obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
public IEnumerable<T> GetItems()
|
public IEnumerable<T> GetItems()
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
using ProjectMotorboat.Exceptions;
|
||||||
|
|
||||||
namespace ProjectMotorboat.CollectionGenericObjects;
|
namespace ProjectMotorboat.CollectionGenericObjects;
|
||||||
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||||
where T : class
|
where T : class
|
||||||
@ -38,70 +40,68 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
_collection = Array.Empty<T?>();
|
_collection = Array.Empty<T?>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public T? Get(int position)
|
public T Get(int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position >= _collection.Length)
|
// TODO выброс ошибки если выход за границу
|
||||||
{
|
// TODO выброс ошибки если объект пустой
|
||||||
return null;
|
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
}
|
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||||
return _collection[position];
|
return _collection[position];
|
||||||
}
|
}
|
||||||
public int Insert(T obj)
|
public int Insert(T obj)
|
||||||
{
|
{
|
||||||
for (int i = 0; i < _collection.Length; i++)
|
// TODO выброс ошибки если переполнение
|
||||||
|
int index = 0;
|
||||||
|
while (index < _collection.Length)
|
||||||
{
|
{
|
||||||
if (_collection[i] == null)
|
if (_collection[index] == null)
|
||||||
{
|
{
|
||||||
_collection[i] = obj;
|
_collection[index] = obj;
|
||||||
return i;
|
return index;
|
||||||
}
|
}
|
||||||
|
++index;
|
||||||
}
|
}
|
||||||
|
throw new CollectionOverflowException(Count);
|
||||||
return -1;
|
|
||||||
}
|
}
|
||||||
public int Insert(T obj, int position)
|
public int Insert(T obj, int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position >= _collection.Length) { return position; }
|
// TODO выброс ошибки если выход за границу
|
||||||
|
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
if (_collection[position] == null)
|
if (_collection[position] == null)
|
||||||
{
|
{
|
||||||
_collection[position] = obj;
|
_collection[position] = obj;
|
||||||
return position;
|
return position;
|
||||||
}
|
}
|
||||||
else
|
int index = position + 1;
|
||||||
|
while (index < _collection.Length)
|
||||||
{
|
{
|
||||||
for (int i = position + 1; i < _collection.Length; i++)
|
if (_collection[index] == null)
|
||||||
{
|
{
|
||||||
if (_collection[i] == null)
|
_collection[index] = obj;
|
||||||
{
|
return index;
|
||||||
_collection[i] = obj;
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = position - 1; i >= 0; i--)
|
|
||||||
{
|
|
||||||
if (_collection[i] == null)
|
|
||||||
{
|
|
||||||
_collection[i] = obj;
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
index++;
|
||||||
}
|
}
|
||||||
|
index = position - 1;
|
||||||
return -1;
|
while (index >= 0)
|
||||||
|
{
|
||||||
|
if (_collection[index] == null)
|
||||||
|
{
|
||||||
|
_collection[index] = obj;
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
index--;
|
||||||
|
}
|
||||||
|
throw new CollectionOverflowException(Count);
|
||||||
}
|
}
|
||||||
public T Remove(int position)
|
public T Remove(int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position >= _collection.Length)
|
// TODO выброс ошибки если объект пустой
|
||||||
{
|
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
return null;
|
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||||
}
|
T removeObj = _collection[position];
|
||||||
|
|
||||||
T? obj = _collection[position];
|
|
||||||
_collection[position] = null;
|
_collection[position] = null;
|
||||||
|
return removeObj;
|
||||||
return obj;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public IEnumerable<T> GetItems()
|
public IEnumerable<T> GetItems()
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
using ProjectMotorboat.Drownings;
|
using ProjectMotorboat.Drownings;
|
||||||
|
using ProjectMotorboat.Exceptions;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
@ -23,8 +24,6 @@ public class StorageCollection<T>
|
|||||||
|
|
||||||
public void AddCollection(string name, CollectionType collectionType)
|
public void AddCollection(string name, CollectionType collectionType)
|
||||||
{
|
{
|
||||||
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
|
|
||||||
// TODO Прописать логику для добавления
|
|
||||||
if (name == null || _storages.ContainsKey(name)) { return; }
|
if (name == null || _storages.ContainsKey(name)) { return; }
|
||||||
switch (collectionType)
|
switch (collectionType)
|
||||||
|
|
||||||
@ -66,22 +65,20 @@ public class StorageCollection<T>
|
|||||||
private readonly string _separatorItems = ";";
|
private readonly string _separatorItems = ";";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Сохранение информации в хранилище в файл
|
/// Сохранение информации по автомобилям в хранилище в файл
|
||||||
/// </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);
|
||||||
}
|
}
|
||||||
|
|
||||||
using (StreamWriter writer = new StreamWriter(filename))
|
using (StreamWriter writer = new StreamWriter(filename))
|
||||||
{
|
{
|
||||||
writer.Write(_collectionKey);
|
writer.Write(_collectionKey);
|
||||||
@ -89,7 +86,6 @@ public class StorageCollection<T>
|
|||||||
{
|
{
|
||||||
StringBuilder sb = new();
|
StringBuilder sb = new();
|
||||||
sb.Append(Environment.NewLine);
|
sb.Append(Environment.NewLine);
|
||||||
|
|
||||||
if (value.Value.Count == 0)
|
if (value.Value.Count == 0)
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
@ -115,35 +111,35 @@ public class StorageCollection<T>
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Загрузка информации в хранилище из файла
|
/// Загрузка информации по автомобилям в хранилище из файла
|
||||||
/// </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("Файл не существует");
|
||||||
}
|
}
|
||||||
using (StreamReader fs = File.OpenText(filename))
|
using (StreamReader fs = File.OpenText(filename))
|
||||||
{
|
{
|
||||||
string str = fs.ReadLine();
|
string str = fs.ReadLine();
|
||||||
if (str == null || str.Length == 0)
|
if (str == null || str.Length == 0)
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("В файле нет данных");
|
||||||
}
|
}
|
||||||
if (!str.StartsWith(_collectionKey))
|
if (!str.StartsWith(_collectionKey))
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("В файле неверные данные");
|
||||||
}
|
}
|
||||||
_storages.Clear();
|
_storages.Clear();
|
||||||
string strs = "";
|
string strs = "";
|
||||||
while ((strs = fs.ReadLine()) != null)
|
while ((strs = fs.ReadLine()) != null)
|
||||||
{
|
{
|
||||||
|
|
||||||
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||||
if (record.Length != 4)
|
if (record.Length != 4)
|
||||||
{
|
{
|
||||||
@ -153,23 +149,30 @@ public class StorageCollection<T>
|
|||||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
ICollectionGenericObjects<T>? collection = 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, StringSplitOptions.RemoveEmptyEntries);
|
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||||
foreach (string elem in set)
|
foreach (string elem in set)
|
||||||
{
|
{
|
||||||
if (elem?.CreateDrawningBoat() is T militaryAircraft)
|
if (elem?.CreateDrawningBoat() is T track)
|
||||||
{
|
{
|
||||||
if (collection.Insert(militaryAircraft) == -1)
|
try
|
||||||
{
|
{
|
||||||
return false;
|
if (collection.Insert(track) == -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)
|
||||||
|
@ -0,0 +1,22 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace ProjectMotorboat.Exceptions;
|
||||||
|
|
||||||
|
[Serializable]
|
||||||
|
internal class CollectionOverflowException : ApplicationException
|
||||||
|
{
|
||||||
|
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество count" + 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,21 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace ProjectMotorboat.Exceptions;
|
||||||
|
[Serializable]
|
||||||
|
internal class ObjectNotFoundException : ApplicationException
|
||||||
|
{
|
||||||
|
public ObjectNotFoundException(int i) : base("В коллекции превышено допустимое количество count" + 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,22 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace ProjectMotorboat.Exceptions;
|
||||||
|
[Serializable]
|
||||||
|
|
||||||
|
internal class PositionOutOfCollectionException : ApplicationException
|
||||||
|
{
|
||||||
|
public PositionOutOfCollectionException(int i) : base("В коллекции превышено допустимое количество count" + 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,84 +1,66 @@
|
|||||||
using ProjectMotorboat.CollectionGenericObjects;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using ProjectMotorboat.CollectionGenericObjects;
|
||||||
using ProjectMotorboat.Drownings;
|
using ProjectMotorboat.Drownings;
|
||||||
|
using ProjectMotorboat.Exceptions;
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
|
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
|
||||||
|
|
||||||
namespace ProjectMotorboat;
|
namespace ProjectMotorboat;
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Форма работы с компанией и ее коллекцией
|
|
||||||
/// </summary>
|
|
||||||
public partial class FormBoatCollection : Form
|
public partial class FormBoatCollection : Form
|
||||||
{
|
{
|
||||||
private readonly StorageCollection<DrawningBoat> _storageCollection;
|
private readonly StorageCollection<DrawningBoat> _storageCollection;
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Компания
|
|
||||||
/// </summary>
|
|
||||||
private AbstractCompany? _company = null;
|
private AbstractCompany? _company = null;
|
||||||
|
|
||||||
/// <summary>
|
private readonly ILogger _logger;
|
||||||
/// Конструктор
|
|
||||||
/// </summary>
|
public FormBoatCollection(ILogger<FormBoatCollection> logger)
|
||||||
public FormBoatCollection()
|
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
_storageCollection = new();
|
_storageCollection = new();
|
||||||
|
_logger = logger;
|
||||||
|
_logger.LogInformation("Форма загрузилась");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Выбор компании
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="sender"></param>
|
|
||||||
/// <param name="e"></param>
|
|
||||||
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
|
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
panelCompanyTools.Enabled = false;
|
panelCompanyTools.Enabled = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Добавление обычного автомобиля
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="sender"></param>
|
|
||||||
/// <param name="e"></param>
|
|
||||||
private void ButtonAddBoat_Click(object sender, EventArgs e)
|
private void ButtonAddBoat_Click(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
FormBoatConfig form = new();
|
FormBoatConfig form = new();
|
||||||
// TODO передать метод
|
form.Show();
|
||||||
form.AddEvent(SetBoat);
|
form.AddEvent(SetBoat);
|
||||||
|
|
||||||
form.Show();
|
|
||||||
}
|
}
|
||||||
private void SetBoat(DrawningBoat? boat)
|
private void SetBoat(DrawningBoat? boat)
|
||||||
{
|
{
|
||||||
if (_company == null || boat == null)
|
try
|
||||||
{
|
{
|
||||||
return;
|
if (_company == null || boat == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (_company + boat != -1)
|
||||||
|
{
|
||||||
|
MessageBox.Show("Объект добавлен");
|
||||||
|
pictureBox.Image = _company.Show();
|
||||||
|
_logger.LogInformation("Добавлен объект: " + boat.GetDataForSave());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
catch (ObjectNotFoundException) { }
|
||||||
if (_company + boat != -1)
|
catch (CollectionOverflowException ex)
|
||||||
{
|
|
||||||
MessageBox.Show("Объект добавлен");
|
|
||||||
pictureBox.Image = _company.Show();
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось добавить объект");
|
MessageBox.Show("Не удалось добавить объект");
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Создание объекта класса-перемещения
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="type">Тип создаваемого объекта</param>
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Удаление объекта
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="sender"></param>
|
|
||||||
/// <param name="e"></param>
|
|
||||||
private void ButtonRemoveBoat_Click(object sender, EventArgs e)
|
private void ButtonRemoveBoat_Click(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
|
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
|
||||||
@ -92,22 +74,23 @@ public partial class FormBoatCollection : Form
|
|||||||
}
|
}
|
||||||
|
|
||||||
int pos = Convert.ToInt32(maskedTextBox.Text);
|
int pos = Convert.ToInt32(maskedTextBox.Text);
|
||||||
if (_company - pos != null)
|
try
|
||||||
{
|
{
|
||||||
MessageBox.Show("Объект удален");
|
if (_company - pos != null)
|
||||||
pictureBox.Image = _company.Show();
|
{
|
||||||
|
MessageBox.Show("Объект удален");
|
||||||
|
pictureBox.Image = _company.Show();
|
||||||
|
_logger.LogInformation("Удален объект по позиции " + pos);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось удалить объект");
|
MessageBox.Show("Не удалось удалить объект");
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Передача объекта в другую форму
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="sender"></param>
|
|
||||||
/// <param name="e"></param>
|
|
||||||
private void ButtonGoToCheck_Click(object sender, EventArgs e)
|
private void ButtonGoToCheck_Click(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
if (_company == null)
|
if (_company == null)
|
||||||
@ -117,33 +100,31 @@ public partial class FormBoatCollection : Form
|
|||||||
|
|
||||||
DrawningBoat? boat = null;
|
DrawningBoat? boat = null;
|
||||||
int counter = 100;
|
int counter = 100;
|
||||||
while (boat == null)
|
try
|
||||||
{
|
{
|
||||||
boat = _company.GetRandomObject();
|
while (boat == null)
|
||||||
counter--;
|
|
||||||
if (counter <= 0)
|
|
||||||
{
|
{
|
||||||
break;
|
boat = _company.GetRandomObject();
|
||||||
|
counter--;
|
||||||
|
if (counter <= 0)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
FormMotorboat Form = new()
|
||||||
|
{
|
||||||
|
SetBoat = boat
|
||||||
|
};
|
||||||
|
Form.ShowDialog();
|
||||||
}
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
|
||||||
if (boat == null)
|
|
||||||
{
|
{
|
||||||
return;
|
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
}
|
}
|
||||||
|
|
||||||
FormMotorboat form = new()
|
|
||||||
{
|
|
||||||
SetBoat = boat
|
|
||||||
};
|
|
||||||
form.ShowDialog();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Перерисовка коллекции
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="sender"></param>
|
|
||||||
/// <param name="e"></param>
|
|
||||||
private void ButtonRefresh_Click(object sender, EventArgs e)
|
private void ButtonRefresh_Click(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
if (_company == null)
|
if (_company == null)
|
||||||
@ -162,33 +143,53 @@ public partial class FormBoatCollection : Form
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
CollectionType collectionType = CollectionType.None;
|
try
|
||||||
if (radioButtonMassive.Checked)
|
|
||||||
{
|
{
|
||||||
collectionType = CollectionType.Massive;
|
CollectionType collectionType = CollectionType.None;
|
||||||
|
if (radioButtonMassive.Checked)
|
||||||
|
{
|
||||||
|
collectionType = CollectionType.Massive;
|
||||||
|
}
|
||||||
|
else if (radioButtonList.Checked)
|
||||||
|
{
|
||||||
|
collectionType = CollectionType.List;
|
||||||
|
}
|
||||||
|
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||||
|
RerfreshListBoxItems();
|
||||||
|
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
|
||||||
}
|
}
|
||||||
else if (radioButtonList.Checked)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
collectionType = CollectionType.List;
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
|
|
||||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ButtonCollectionDel_Click(object sender, EventArgs e)
|
private void ButtonCollectionDel_Click(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
if (listBoxCollection.SelectedItem == null)
|
|
||||||
|
|
||||||
|
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Коллекция не выбрана");
|
MessageBox.Show("Коллекция не выбрана");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
|
||||||
|
try
|
||||||
{
|
{
|
||||||
return;
|
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||||
|
RerfreshListBoxItems();
|
||||||
|
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
|
||||||
}
|
}
|
||||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
catch (Exception ex)
|
||||||
RerfreshListBoxItems();
|
{
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void RerfreshListBoxItems()
|
private void RerfreshListBoxItems()
|
||||||
@ -234,13 +235,16 @@ public partial class FormBoatCollection : Form
|
|||||||
{
|
{
|
||||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||||
{
|
{
|
||||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
try
|
||||||
{
|
{
|
||||||
|
_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(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -249,15 +253,20 @@ public partial class FormBoatCollection : 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);
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
|
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
|
||||||
}
|
}
|
||||||
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 ProjectMotorboat
|
namespace ProjectMotorboat
|
||||||
{
|
{
|
||||||
internal static class Program
|
internal static class Program
|
||||||
@ -10,8 +14,21 @@ namespace ProjectMotorboat
|
|||||||
{
|
{
|
||||||
// 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.
|
||||||
|
ServiceCollection services = new();
|
||||||
ApplicationConfiguration.Initialize();
|
ApplicationConfiguration.Initialize();
|
||||||
Application.Run(new FormBoatCollection());
|
ConfigureServices(services);
|
||||||
|
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||||
|
Application.Run(serviceProvider.GetRequiredService<FormBoatCollection>());
|
||||||
}
|
}
|
||||||
|
private static void ConfigureServices(ServiceCollection services)
|
||||||
|
{
|
||||||
|
services.AddSingleton<FormBoatCollection>()
|
||||||
|
.AddLogging(option =>
|
||||||
|
{
|
||||||
|
option.SetMinimumLevel(LogLevel.Information);
|
||||||
|
option.AddNLog("nlog.config");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -8,4 +8,17 @@
|
|||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
|
||||||
|
<PackageReference Include="NLog" Version="5.3.2" />
|
||||||
|
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.10" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Update="nlog.config">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
15
ProjectMotorboat/ProjectMotorboat/nlog.config
Normal file
15
ProjectMotorboat/ProjectMotorboat/nlog.config
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
<?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>
|
Loading…
x
Reference in New Issue
Block a user