Поделал лаб07
This commit is contained in:
parent
bf7ba3ecc4
commit
b614557ff8
@ -34,7 +34,7 @@ public abstract class AbstractCompany
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight)) - 13;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Конструктор
|
/// Конструктор
|
||||||
@ -95,8 +95,12 @@ public abstract class AbstractCompany
|
|||||||
SetObjectsPosition();
|
SetObjectsPosition();
|
||||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||||
{
|
{
|
||||||
DrawingBasicSeaplane? obj = _collection?.Get(i);
|
|
||||||
obj?.DrawTransport(graphics);
|
try {
|
||||||
|
DrawingBasicSeaplane? obj = _collection?.Get(i);
|
||||||
|
obj?.DrawTransport(graphics);
|
||||||
|
}
|
||||||
|
catch (Exception) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
return bitmap;
|
return bitmap;
|
||||||
|
@ -1,4 +1,8 @@
|
|||||||
namespace ProjectSeaplane.CollectionGenericObjects;
|
|
||||||
|
using ProjectSeaplane.Exceptions;
|
||||||
|
|
||||||
|
|
||||||
|
namespace ProjectSeaplane.CollectionGenericObjects;
|
||||||
|
|
||||||
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||||
where T : class
|
where T : class
|
||||||
@ -38,14 +42,14 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
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 вставка в конец набора
|
// TODO вставка в конец набора
|
||||||
if (Count == _maxCount) return -1;
|
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||||
_collection.Add(obj);
|
_collection.Add(obj);
|
||||||
return Count;
|
return Count;
|
||||||
}
|
}
|
||||||
@ -54,8 +58,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
// TODO проверка, что не превышено максимальное количество элементов
|
// TODO проверка, что не превышено максимальное количество элементов
|
||||||
// TODO проверка позиции
|
// TODO проверка позиции
|
||||||
// TODO вставка по позиции
|
// TODO вставка по позиции
|
||||||
if (Count == _maxCount) return -1;
|
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||||
if (position >= Count || position < 0) return -1;
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
_collection.Insert(position, obj);
|
_collection.Insert(position, obj);
|
||||||
return position;
|
return position;
|
||||||
}
|
}
|
||||||
@ -63,7 +67,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
{
|
{
|
||||||
// TODO проверка позиции
|
// TODO проверка позиции
|
||||||
// TODO удаление объекта из списка
|
// TODO удаление объекта из списка
|
||||||
if (position >= Count || position < 0) return null;
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
T obj = _collection[position];
|
T obj = _collection[position];
|
||||||
_collection.RemoveAt(position);
|
_collection.RemoveAt(position);
|
||||||
return obj;
|
return obj;
|
||||||
|
@ -1,4 +1,7 @@
|
|||||||
namespace ProjectSeaplane.CollectionGenericObjects;
|
|
||||||
|
using ProjectSeaplane.Exceptions;
|
||||||
|
|
||||||
|
namespace ProjectSeaplane.CollectionGenericObjects;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Параметризованный набор объектов
|
/// Параметризованный набор объектов
|
||||||
@ -48,11 +51,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
|
|
||||||
public T? Get(int position)
|
public T? Get(int position)
|
||||||
{
|
{
|
||||||
// TODO проверка позиции
|
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
if (position >= _collection.Length || position < 0)
|
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return _collection[position];
|
return _collection[position];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -70,7 +70,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
|
|
||||||
index++;
|
index++;
|
||||||
}
|
}
|
||||||
return -1;
|
throw new CollectionOverflowException(Count);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj, int position)
|
public int Insert(T obj, int position)
|
||||||
@ -81,8 +81,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
// если нет после, ищем до
|
// если нет после, ищем до
|
||||||
// TODO вставка
|
// TODO вставка
|
||||||
if (position >= _collection.Length || position < 0)
|
if (position >= _collection.Length || position < 0)
|
||||||
{
|
{
|
||||||
return -1;
|
throw new PositionOutOfCollectionException(position);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_collection[position] == null)
|
if (_collection[position] == null)
|
||||||
@ -109,17 +109,15 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
return position;
|
return position;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return -1;
|
throw new CollectionOverflowException(Count);
|
||||||
}
|
}
|
||||||
|
|
||||||
public T Remove(int position)
|
public T Remove(int position)
|
||||||
{
|
{
|
||||||
// TODO проверка позиции
|
// TODO проверка позиции
|
||||||
// TODO удаление объекта из массива, присвоив элементу массива значение null
|
// TODO удаление объекта из массива, присвоив элементу массива значение null
|
||||||
if (position >= _collection.Length || position < 0)
|
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
{
|
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||||
return null;
|
|
||||||
}
|
|
||||||
T obj = _collection[position];
|
T obj = _collection[position];
|
||||||
_collection[position] = null;
|
_collection[position] = null;
|
||||||
return obj;
|
return obj;
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
using ProjectSeaplane.Drawnings;
|
using ProjectSeaplane.Drawnings;
|
||||||
|
using ProjectSeaplane.Exceptions;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
@ -49,11 +50,18 @@ public class PlanePark : AbstractCompany
|
|||||||
}
|
}
|
||||||
for (int x = _pictureWidth - 200; x - 120 > 0; x -= _placeSizeHeight + 75)
|
for (int x = _pictureWidth - 200; x - 120 > 0; x -= _placeSizeHeight + 75)
|
||||||
{
|
{
|
||||||
_collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight);
|
if (count < _collection?.Count)
|
||||||
_collection?.Get(count)?.SetPosition(x, y);
|
{
|
||||||
count++;
|
try
|
||||||
|
{
|
||||||
|
_collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight);
|
||||||
|
_collection?.Get(count)?.SetPosition(x, y);
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
catch (ObjectNotFoundException) { }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
using ProjectSeaplane.Drawnings;
|
using ProjectSeaplane.Drawnings;
|
||||||
|
using ProjectSeaplane.Exceptions;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
namespace ProjectSeaplane.CollectionGenericObjects;
|
namespace ProjectSeaplane.CollectionGenericObjects;
|
||||||
@ -92,11 +93,11 @@ public class StorageCollection<T>
|
|||||||
/// <param name="filename">Путь и имя файла</param>
|
/// <param name="filename">Путь и имя файла</param>
|
||||||
/// <returns>true - сохранение прошло успешно, false - ошибка при
|
/// <returns>true - сохранение прошло успешно, false - ошибка при
|
||||||
///сохранении данных</returns>
|
///сохранении данных</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))
|
||||||
{
|
{
|
||||||
@ -134,29 +135,29 @@ public class StorageCollection<T>
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Загрузка информации по автомобилям в хранилище из файла
|
/// Загрузка информации по автомобилям в хранилище из файла
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="filename">Путь и имя файла</param>/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке
|
/// <param name="filename">Путь и имя файла</param>/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке
|
||||||
///данных</returns>
|
///данных</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 = "";
|
||||||
@ -172,7 +173,7 @@ 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);
|
||||||
@ -180,15 +181,21 @@ public class StorageCollection<T>
|
|||||||
{
|
{
|
||||||
if (elem?.CreateDrawningBasicSeaplane() is T seaplane)
|
if (elem?.CreateDrawningBasicSeaplane() is T seaplane)
|
||||||
{
|
{
|
||||||
if (collection.Insert(seaplane) == -1)
|
try
|
||||||
{
|
{
|
||||||
return false;
|
if (collection.Insert(seaplane) == -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;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
@ -0,0 +1,25 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
|
||||||
|
namespace ProjectSeaplane.Exceptions;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Класс, описывающий ошибку переполнения коллекции
|
||||||
|
/// </summary>
|
||||||
|
[Serializable]
|
||||||
|
internal 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,25 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
|
||||||
|
namespace ProjectSeaplane.Exceptions;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
|
||||||
|
/// </summary>
|
||||||
|
[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) { }
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace ProjectSeaplane.Exceptions;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Класс, описывающий ошибку выхода за границы коллекции
|
||||||
|
/// </summary>
|
||||||
|
[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) { }
|
||||||
|
}
|
@ -1,5 +1,8 @@
|
|||||||
using ProjectSeaplane.CollectionGenericObjects;
|
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using ProjectSeaplane.CollectionGenericObjects;
|
||||||
using ProjectSeaplane.Drawnings;
|
using ProjectSeaplane.Drawnings;
|
||||||
|
using ProjectSeaplane.Exceptions;
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
|
|
||||||
namespace ProjectSeaplane;
|
namespace ProjectSeaplane;
|
||||||
@ -19,13 +22,16 @@ public partial class FormPlaneCollection : Form
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
AbstractCompany? _company = null;
|
AbstractCompany? _company = null;
|
||||||
|
|
||||||
|
private readonly ILogger _logger;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Конструктор
|
/// Конструктор
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public FormPlaneCollection()
|
public FormPlaneCollection(ILogger<FormPlaneCollection> logger)
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
_storageCollection = new();
|
_storageCollection = new();
|
||||||
|
_logger = logger;
|
||||||
|
_logger.LogInformation("Форма загрузилась");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -56,19 +62,30 @@ public partial class FormPlaneCollection : Form
|
|||||||
/// <param name="plane"></param>
|
/// <param name="plane"></param>
|
||||||
private void SetPlane(DrawingBasicSeaplane plane)
|
private void SetPlane(DrawingBasicSeaplane plane)
|
||||||
{
|
{
|
||||||
if (_company == null || plane == null)
|
try
|
||||||
{
|
{
|
||||||
return;
|
if (_company == null || plane == null)
|
||||||
}
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (_company + plane != -1)
|
if (_company + plane != -1)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Объект добавлен");
|
MessageBox.Show("Объект добавлен");
|
||||||
pictureBox.Image = _company.Show();
|
pictureBox.Image = _company.Show();
|
||||||
|
_logger.LogInformation("Добавлен объект: " + plane.GetDataForSave());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else
|
catch (ObjectNotFoundException) { }
|
||||||
|
catch (CollectionOverflowException ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось добавить объект");
|
MessageBox.Show("Не удалось добавить объект");
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
|
}
|
||||||
|
catch (PositionOutOfCollectionException ex)
|
||||||
|
{
|
||||||
|
MessageBox.Show("Выход за границы коллекции");
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -91,14 +108,19 @@ public partial class FormPlaneCollection : 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -116,26 +138,34 @@ public partial class FormPlaneCollection : Form
|
|||||||
|
|
||||||
DrawingBasicSeaplane? seaplane = null;
|
DrawingBasicSeaplane? seaplane = null;
|
||||||
int counter = 100;
|
int counter = 100;
|
||||||
while (seaplane == null)
|
|
||||||
|
try
|
||||||
{
|
{
|
||||||
seaplane = _company.GetRandomObject();
|
while (seaplane == null)
|
||||||
counter--;
|
|
||||||
if (counter <= 0)
|
|
||||||
{
|
{
|
||||||
break;
|
seaplane = _company.GetRandomObject();
|
||||||
|
counter--;
|
||||||
|
if (counter <= 0)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if (seaplane == null)
|
if (seaplane == null)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
FormSeaplane form = new()
|
FormSeaplane form = new()
|
||||||
|
{
|
||||||
|
SetSeaplane = seaplane
|
||||||
|
};
|
||||||
|
form.ShowDialog();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
SetSeaplane = seaplane
|
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
};
|
}
|
||||||
form.ShowDialog();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -168,17 +198,27 @@ public partial class FormPlaneCollection : Form
|
|||||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Обновление списка в ListboxCollection
|
/// Обновление списка в ListboxCollection
|
||||||
@ -208,12 +248,20 @@ public partial class FormPlaneCollection : Form
|
|||||||
MessageBox.Show("Коллекция не выбрана");
|
MessageBox.Show("Коллекция не выбрана");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
try
|
||||||
{
|
{
|
||||||
return;
|
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||||
|
RerfreshListBoxItems();
|
||||||
|
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
|
||||||
RerfreshListBoxItems();
|
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// создание компании
|
/// создание компании
|
||||||
@ -254,15 +302,18 @@ public partial class FormPlaneCollection : Form
|
|||||||
{
|
{
|
||||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||||
{
|
{
|
||||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
try
|
||||||
{
|
{
|
||||||
|
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||||
MessageBox.Show("Сохранение прошло успешно",
|
MessageBox.Show("Сохранение прошло успешно",
|
||||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||||
|
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
|
||||||
}
|
}
|
||||||
else
|
|
||||||
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не сохранилось", "Результат",
|
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -276,18 +327,20 @@ public partial class FormPlaneCollection : Form
|
|||||||
{
|
{
|
||||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||||
{
|
{
|
||||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
try
|
||||||
{
|
{
|
||||||
MessageBox.Show("Загрузка прошла успешно",
|
_storageCollection.LoadData(openFileDialog.FileName);
|
||||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
|
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
|
||||||
}
|
}
|
||||||
else
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не загрузилось", "Результат",
|
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,3 +1,8 @@
|
|||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Serilog;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
|
||||||
namespace ProjectSeaplane
|
namespace ProjectSeaplane
|
||||||
{
|
{
|
||||||
internal static class Program
|
internal static class Program
|
||||||
@ -11,7 +16,30 @@ namespace ProjectSeaplane
|
|||||||
// To customize application configuration such as set high DPI settings or default font,
|
// To customize application configuration such as set high DPI settings or default font,
|
||||||
// see https://aka.ms/applicationconfiguration.
|
// see https://aka.ms/applicationconfiguration.
|
||||||
ApplicationConfiguration.Initialize();
|
ApplicationConfiguration.Initialize();
|
||||||
Application.Run(new FormPlaneCollection());
|
ServiceCollection services = new();
|
||||||
|
ConfigureServices(services);
|
||||||
|
using ServiceProvider servicesProvider = services.BuildServiceProvider();
|
||||||
|
Application.Run(servicesProvider.GetRequiredService<FormPlaneCollection>());
|
||||||
|
}
|
||||||
|
private static void ConfigureServices(ServiceCollection services)
|
||||||
|
{
|
||||||
|
string[] path = Directory.GetCurrentDirectory().Split('\\');
|
||||||
|
string pathNeed = "";
|
||||||
|
for (int i = 0; i < path.Length - 3; i++)
|
||||||
|
{
|
||||||
|
pathNeed += path[i] + "\\";
|
||||||
|
}
|
||||||
|
services.AddSingleton<FormPlaneCollection>()
|
||||||
|
.AddLogging(option =>
|
||||||
|
{
|
||||||
|
option.SetMinimumLevel(LogLevel.Information);
|
||||||
|
option.AddSerilog(new LoggerConfiguration()
|
||||||
|
.ReadFrom.Configuration(new ConfigurationBuilder()
|
||||||
|
.AddJsonFile($"{pathNeed}serilog.json")
|
||||||
|
.Build())
|
||||||
|
.CreateLogger());
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -8,6 +8,17 @@
|
|||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
|
||||||
|
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||||
|
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Compile Update="Properties\Resources.Designer.cs">
|
<Compile Update="Properties\Resources.Designer.cs">
|
||||||
<DesignTime>True</DesignTime>
|
<DesignTime>True</DesignTime>
|
||||||
@ -23,4 +34,10 @@
|
|||||||
</EmbeddedResource>
|
</EmbeddedResource>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Update="serilog.json">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
15
ProjectSeaplane/ProjectSeaplane/serilog.json
Normal file
15
ProjectSeaplane/ProjectSeaplane/serilog.json
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"Serilog": {
|
||||||
|
"Using": [ "Serilog.Sinks.File" ],
|
||||||
|
"MinimumLevel": "Debug",
|
||||||
|
"WriteTo": [
|
||||||
|
{
|
||||||
|
"Name": "File",
|
||||||
|
"Args": { "path": "log.log" }
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"Properties": {
|
||||||
|
"Application": "Sample"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user