diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs
index b8f6cd8..c85dc44 100644
--- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs
+++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs
@@ -1,9 +1,12 @@
using ProjectLiner.Drawnings;
+using ProjectLiner.Exceptions;
+using ProjectLiner.CollectionGenericObjects;
+using ProjectLiner.Exceptions;
namespace ProjectLiner.CollectionGenericObjects
{
///
- /// Абстракция компании, хранящий коллекцию лайнеров
+ /// Абстракция компании, хранящий коллекцию автомобилей
///
public abstract class AbstractCompany
{
@@ -15,7 +18,7 @@ namespace ProjectLiner.CollectionGenericObjects
///
/// Размер места (высота)
///
- protected readonly int _placeSizeHeight = 110;
+ protected readonly int _placeSizeHeight = 150;
///
/// Ширина окна
@@ -28,21 +31,21 @@ namespace ProjectLiner.CollectionGenericObjects
protected readonly int _pictureHeight;
///
- /// Коллекция лайнеров
+ /// Коллекция автомобилей
///
protected ICollectionGenericObjects? _collection = null;
///
/// Вычисление максимального количества элементов, который можно разместить в окне
///
- private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
+ private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _placeSizeHeight);
///
/// Конструктор
///
/// Ширина окна
/// Высота окна
- /// Коллекция лайнеров
+ /// Коллекция автомобилей
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection)
{
_pictureWidth = picWidth;
@@ -55,12 +58,11 @@ namespace ProjectLiner.CollectionGenericObjects
/// Перегрузка оператора сложения для класса
///
/// Компания
- /// Добавляемый объект
+ /// Добавляемый объект
///
-
- public static int operator +(AbstractCompany company, DrawningCommonLiner airplan)
+ public static int operator +(AbstractCompany company, DrawningCommonLiner airplane)
{
- return company._collection.Insert(airplan);
+ return company._collection.Insert(airplane);
}
///
@@ -71,7 +73,7 @@ namespace ProjectLiner.CollectionGenericObjects
///
public static DrawningCommonLiner operator -(AbstractCompany company, int position)
{
- return company._collection.Remove(position) ;
+ return company._collection.Remove(position);
}
///
@@ -81,7 +83,14 @@ namespace ProjectLiner.CollectionGenericObjects
public DrawningCommonLiner? GetRandomObject()
{
Random rnd = new();
- return _collection?.Get(rnd.Next(GetMaxCount));
+ try
+ {
+ return _collection?.Get(rnd.Next(GetMaxCount));
+ }
+ catch (ObjectNotFoundException)
+ {
+ return null;
+ }
}
///
@@ -97,8 +106,15 @@ namespace ProjectLiner.CollectionGenericObjects
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
- DrawningCommonLiner? obj = _collection?.Get(i);
- obj?.DrawTransport(graphics);
+ try
+ {
+ DrawningCommonLiner? obj = _collection?.Get(i);
+ obj?.DrawTransport(graphics);
+ }
+ catch (ObjectNotFoundException)
+ {
+ continue;
+ }
}
return bitmap;
diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/LinerSharingService.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/LinerSharingService.cs
index ad2d528..0d43197 100644
--- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/LinerSharingService.cs
+++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/LinerSharingService.cs
@@ -1,64 +1,67 @@
using ProjectLiner.Drawnings;
+using ProjectLiner.Exceptions;
+using ProjectLiner.CollectionGenericObjects;
+using ProjectLiner.Exceptions;
-namespace ProjectLiner.CollectionGenericObjects;
-
-///
-/// Реализация абстрактной компании - лайнер
-///
-public class LinerSharingService : AbstractCompany
+namespace ProjectLiner.CollectionGenericObjects
{
- ///
- /// Конструктор
- ///
- /// Ширина
- /// Высота
- /// Коллекция
- public LinerSharingService(int picWidth, int picHeight, ICollectionGenericObjects collection) : base(picWidth, picHeight, collection)
- {
- }
- protected override void DrawBackgound(Graphics g)
+ public class LinerSharingService : AbstractCompany
{
- Pen pen = new(Color.Black, 4);
- for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
+ public LinerSharingService(int picWidth, int picHeight, ICollectionGenericObjects collection) : base(picWidth, picHeight, collection)
{
- for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
+ }
+
+ protected override void DrawBackgound(Graphics g)
+ {
+ Pen pen = new(Color.Black, 4);
+ for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
- g.DrawLine(pen, i * _placeSizeWidth, (int)(j * _placeSizeHeight * 1.3),
- i * _placeSizeWidth + _placeSizeWidth - 40, (int)(j * _placeSizeHeight * 1.3));
+ for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
+ {
+ g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight,
+ i * _placeSizeWidth + _placeSizeWidth - 40, j * _placeSizeHeight);
+ }
+ g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
+ }
+ }
+
+ protected override void SetObjectsPosition()
+ {
+ int width = _pictureWidth / _placeSizeWidth;
+ int height = _pictureHeight / _placeSizeHeight;
+
+ int curWidth = width - 1;
+ int curHeight = 0;
+
+ for (int i = 0; i < (_collection?.Count ?? 0); i++)
+ {
+ try
+ {
+ if (_collection.Get(i) != null)
+ {
+ _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
+ _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 5);
+ }
+
+ if (curWidth > 0)
+ curWidth--;
+ else
+ {
+ curWidth = width - 1;
+ curHeight++;
+ }
+ if (curHeight > height)
+ {
+ return;
+ }
+ }
+ catch (ObjectNotFoundException)
+ {
+ break;
+ }
}
- g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
-
- protected override void SetObjectsPosition()
- {
- int width = _pictureWidth / _placeSizeWidth;
- int height = _pictureHeight / _placeSizeHeight;
-
- int curWidth = width - 1;
- int curHeight = 0;
-
- for (int i = 0; i < (_collection?.Count ?? 0); i++)
- {
- if (_collection?.Get(i) != null)
- {
- _collection.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
- _collection.Get(i)?.SetPosition(_placeSizeWidth * curWidth + 10, (int)(curHeight * _placeSizeHeight * 1.3));
- }
-
- if (curWidth > 0)
- curWidth--;
- else
- {
- curWidth = width - 1;
- curHeight++;
- }
- if (curHeight > height)
- {
- return;
- }
- }
- }
}
\ No newline at end of file
diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs
index 0e75629..d37225b 100644
--- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs
+++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs
@@ -1,76 +1,97 @@
-using ProjectLiner.CollectionGenericObjects;
+
+using ProjectLiner.Exceptions;
+using ProjectLiner.CollectionGenericObjects;
+using ProjectLiner.Exceptions;
-///
-/// Параметризованный набор объектов
-///
-/// Параметр: ограничение - ссылочный тип
-public class ListGenericObjects : ICollectionGenericObjects
- where T : class
+namespace ProjectLiner.CollectionGenericObjects
{
///
- /// Список объектов, которые храним
+ /// Параметризованный набор объектов
///
- private readonly Dictionary _collection;
- ///
- /// Максимально допустимое число объектов в списке
- ///
- private int _maxCount;
- public int Count => _collection.Keys.Count;
- public int MaxCount
+ /// Параметр: ограничение - ссылочный тип
+ public class ListGenericObjects : ICollectionGenericObjects
+ where T : class
{
- get
+ ///
+ /// Список объектов, которые храним
+ ///
+ private readonly List _collection;
+
+ ///
+ /// Максимально допустимое число объектов в списке
+ ///
+ private int _maxCount;
+
+ public int Count => _collection.Count;
+
+ public int MaxCount
{
- return _maxCount;
+ get
+ {
+ return _maxCount;
+ }
+
+ set
+ {
+ if (value > 0)
+ {
+ _maxCount = value;
+ }
+ }
}
- set
+ public CollectionType GetCollectionType => CollectionType.List;
+
+ ///
+ /// Конструктор
+ ///
+ public ListGenericObjects()
{
- if (value > 0)
+ _collection = new();
+ }
+
+ public T? Get(int position)
+ {
+ if (position >= Count || position < 0)
+ throw new PositionOutOfCollectionException(position);
+
+ return _collection[position];
+ }
+
+ public int Insert(T obj)
+ {
+ if (Count >= _maxCount)
+ throw new CollectionOverflowException(Count);
+ _collection.Add(obj);
+ return Count;
+ }
+
+ public int Insert(T obj, int position)
+ {
+ if (Count == _maxCount)
+ throw new CollectionOverflowException(Count);
+ if (position < 0 || position > Count)
+ throw new PositionOutOfCollectionException(position); ;
+ _collection.Insert(position, obj);
+ return position;
+ }
+
+ public T? Remove(int position)
+ {
+ if (position < 0 || position > Count)
+ throw new PositionOutOfCollectionException(position);
+
+ T? temp = _collection[position];
+ _collection.RemoveAt(position);
+ return temp;
+ }
+
+ public IEnumerable GetItems()
+ {
+ for (int i = 0; i < _collection.Count; ++i)
{
- _maxCount = value;
+ yield return _collection[i];
}
}
}
-
- public CollectionType GetCollectionType => CollectionType.List;
-
- ///
- /// Конструктор
- ///
- public ListGenericObjects()
- {
- _collection = new();
- }
- public T? Get(int position)
- {
- if (position >= Count || position < 0) return null;
- return _collection[position];
- }
- public int Insert(T obj)
- {
- if (Count > _maxCount) return -1;
- _collection[Count-1] = obj;
- return Count;
- }
- public int Insert(T obj, int position)
- {
- if (Count > _maxCount) return -1;
- _collection[position] = obj;
- return 1;
- }
- public T? Remove(int position)
- {
- if (_collection.ContainsKey(position)) return null;
- T? temp = _collection[position];
- _collection.Remove(position);
- return temp;
- }
-
- public IEnumerable GetItems()
- {
- for (int i = 0; i < _collection.Count; ++i)
- {
- yield return _collection[i];
- }
- }
-}
\ No newline at end of file
+}
diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs
index 8c51a0a..99f8a17 100644
--- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -1,4 +1,8 @@
+using ProjectLiner.Exceptions;
+using ProjectLiner.CollectionGenericObjects;
+using ProjectLiner.Exceptions;
+
namespace ProjectLiner.CollectionGenericObjects
{
///
@@ -12,7 +16,7 @@ namespace ProjectLiner.CollectionGenericObjects
/// Массив объектов, которые храним
///
private T?[] _collection;
-
+
public int Count => _collection.Length;
public int MaxCount
@@ -51,7 +55,9 @@ namespace ProjectLiner.CollectionGenericObjects
public T? Get(int position)
{
if (position < 0 || position >= Count)
- return null;
+ throw new PositionOutOfCollectionException(position);
+ if (_collection[position] == null)
+ throw new ObjectNotFoundException(position);
return _collection[position];
}
@@ -65,17 +71,20 @@ namespace ProjectLiner.CollectionGenericObjects
return i;
}
}
- return -1;
+ throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
- if (position >= Count || position < 0) return -1;
+ if (position >= Count || position < 0)
+ throw new PositionOutOfCollectionException(position);
+
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
+
int temp = position + 1;
while (temp < Count)
{
@@ -84,29 +93,30 @@ namespace ProjectLiner.CollectionGenericObjects
_collection[temp] = obj;
return temp;
}
- ++temp;
+ temp++;
}
+
temp = position - 1;
- while (temp >= 0)
+ while (temp > 0)
{
if (_collection[temp] == null)
{
_collection[temp] = obj;
return temp;
}
- --temp;
+ temp--;
}
- return -1;
+
+ throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
if (position < 0 || position >= Count)
- {
- return null;
- }
+ throw new PositionOutOfCollectionException(position);
- //if (_collection[position] == null) return null;
+ if (_collection[position] == null)
+ throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null;
diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs
index 08bacf4..c434e79 100644
--- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs
+++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs
@@ -1,208 +1,226 @@
-using ProjectLiner.CollectionGenericObjects;
+using System.Data;
+using System.IO;
+using System.Text;
using ProjectLiner.Drawnings;
+using ProjectLiner.Exceptions;
+using ProjectLiner.CollectionGenericObjects;
+using ProjectLiner.Exceptions;
-///
-/// Класс-хранилище коллекций
-///
-///
-public class StorageCollection
- where T : DrawningCommonLiner
+namespace ProjectLiner.CollectionGenericObjects
{
///
- /// Словарь (хранилище) с коллекциями
+ /// Класс-хранилище коллекций
///
- readonly Dictionary> _storages;
-
- ///
- /// Возвращение списка названий коллекций
- ///
- public List Keys => _storages.Keys.ToList();
-
- ///
- /// Ключевое слово, с которого должен начинаться файл
- ///
- private readonly string _collectionKey = "CollectionsStorage";
-
- ///
- /// Разделитель для записи ключа и значения элемента словаря
- ///
- private readonly string _separatorForKeyValue = "|";
-
- ///
- /// Разделитель для записей коллекции данных в файл
- ///
- private readonly string _separatorItems = ";";
-
- ///
- /// Конструктор
- ///
- public StorageCollection()
+ ///
+ public class StorageCollection
+ where T : DrawningCommonLiner
{
- _storages = new Dictionary>();
+ ///
+ /// Словарь (хранилище) с коллекциями
+ ///
+ readonly Dictionary> _storages;
- }
- ///
- /// Добавление коллекции в хранилище
- ///
- /// Название коллекции
- /// тип коллекции
- public void AddCollection(string name, CollectionType collectionType)
- {
- if (name == null || _storages.ContainsKey(name)) { return; }
- switch (collectionType)
+ ///
+ /// Возвращение списка названий коллекций
+ ///
+ public List Keys => _storages.Keys.ToList();
+ ///
+ /// Ключевое слово, с которого должен начинаться файл
+ ///
+ private readonly string _collectionKey = "CollectionsStorage";
+
+ ///
+ /// Разделитель для записи ключа и значения элемента словаря
+ ///
+ private readonly string _separatorForKeyValue = "|";
+
+ ///
+ /// Разделитель для записей коллекции данных в файл
+ ///
+ private readonly string _separatorItems = ";";
+
+ ///
+ /// Конструктор
+ ///
+ public StorageCollection()
{
- case CollectionType.None:
+ _storages = new Dictionary>();
+ }
+
+ ///
+ /// Добавление коллекции в хранилище
+ ///
+ /// Название коллекции
+ /// тип коллекции
+ public void AddCollection(string name, CollectionType collectionType)
+ {
+ if (name == null || _storages.ContainsKey(name))
return;
- case CollectionType.Massive:
- _storages[name] = new MassiveGenericObjects();
- return;
- case CollectionType.List:
- _storages[name] = new ListGenericObjects();
- return;
- }
- }
- ///
- /// Удаление коллекции
- ///
- /// Название коллекции
- public void DelCollection(string name)
- {
- if (_storages.ContainsKey(name))
- _storages.Remove(name);
- }
- ///
- /// Доступ к коллекции
- ///
- /// Название коллекции
- ///
- public ICollectionGenericObjects? this[string name]
- {
- get
- {
- if (name == null || !_storages.ContainsKey(name)) { return null; }
- return _storages[name];
- }
- }
- ///
- /// Сохранение информации по лайнерам в хранилище в файл
- ///
- /// Путь и имя файла
- /// true - сохранение прошло успешно, false - ошибка при сохранении данных
- public bool SaveData(string filename)
- {
- if (_storages.Count == 0)
- return false;
-
- if (File.Exists(filename))
- File.Delete(filename);
-
- using FileStream fs = new(filename, FileMode.Create);
- using StreamWriter sw = new StreamWriter(fs);
- sw.Write(_collectionKey);
- foreach (KeyValuePair> value in _storages)
- {
- sw.Write(Environment.NewLine);
- if (value.Value.Count == 0)
+ switch (collectionType)
{
- continue;
- }
-
- sw.Write(value.Key);
- sw.Write(_separatorForKeyValue);
- sw.Write(value.Value.GetCollectionType);
- sw.Write(_separatorForKeyValue);
- sw.Write(value.Value.MaxCount);
- sw.Write(_separatorForKeyValue);
-
- foreach (T? item in value.Value.GetItems())
- {
- string data = item?.GetDataForSave() ?? string.Empty;
- if (string.IsNullOrEmpty(data))
- {
- continue;
- }
-
- sw.Write(data);
- sw.Write(_separatorItems);
+ case CollectionType.None:
+ return;
+ case CollectionType.Massive:
+ _storages[name] = new MassiveGenericObjects();
+ return;
+ case CollectionType.List:
+ _storages[name] = new ListGenericObjects();
+ return;
}
}
- return true;
- }
- ///
- /// Загрузка информации по лайнерам в хранилище из файла
- ///
- /// Путь и имя файла
- /// true - загрузка прошла успешно, false - ошибка при загрузке данных
- public bool LoadData(string filename)
- {
- if (!File.Exists(filename))
+ ///
+ /// Удаление коллекции
+ ///
+ /// Название коллекции
+ public void DelCollection(string name)
{
- return false;
+ if (_storages.ContainsKey(name))
+ _storages.Remove(name);
}
- using (FileStream fs = new(filename, FileMode.Open))
+ ///
+ /// Доступ к коллекции
+ ///
+ /// Название коллекции
+ ///
+ public ICollectionGenericObjects? this[string name]
{
- using StreamReader sr = new StreamReader(fs);
-
- string str = sr.ReadLine();
- if (str == null || str.Length == 0)
+ get
{
- return false;
+ if (name == null || !_storages.ContainsKey(name))
+ return null;
+
+ return _storages[name];
}
+ }
- if (!str.Equals(_collectionKey))
+ ///
+ /// Сохранение информации по самолетам в хранилище в файл
+ ///
+ /// Путь и имя файла
+ /// true - сохранение прошло успешно, false - ошибка при сохранении данных
+ public void SaveData(string filename)
+ {
+ if (_storages.Count == 0)
+ throw new NullReferenceException("В хранилище отсутствуют коллекции для сохранения");
+
+ if (File.Exists(filename))
+ File.Delete(filename);
+
+
+ using (StreamWriter sw = new(filename))
{
- return false;
- }
- _storages.Clear();
-
- while (!sr.EndOfStream)
- {
- string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
- if (record.Length != 4)
+ sw.Write(_collectionKey);
+ foreach (KeyValuePair> value in _storages)
{
- continue;
- }
-
- CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
- ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType);
- if (collection == null)
- {
- return false;
- }
-
- collection.MaxCount = Convert.ToInt32(record[2]);
-
- string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
- foreach (string elem in set)
- {
- if (elem?.CreateDrawningCommonLiner() is T commonLiner)
+ sw.Write(Environment.NewLine);
+ if (value.Value.Count == 0)
{
- if (collection.Insert(commonLiner) == -1)
- return false;
+ continue;
+ }
+
+ sw.Write(value.Key);
+ sw.Write(_separatorForKeyValue);
+ sw.Write(value.Value.GetCollectionType);
+ sw.Write(_separatorForKeyValue);
+ sw.Write(value.Value.MaxCount);
+ sw.Write(_separatorForKeyValue);
+
+ foreach (T? item in value.Value.GetItems())
+ {
+ string data = item?.GetDataForSave() ?? string.Empty;
+ if (string.IsNullOrEmpty(data))
+ {
+ continue;
+ }
+
+ sw.Write(data);
+ sw.Write(_separatorItems);
}
}
- _storages.Add(record[0], collection);
}
}
- return true;
- }
- ///
- /// Создание коллекции по типу
- ///
- ///
- ///
- private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType)
- {
- return collectionType switch
+ ///
+ /// Загрузка информации по самолетам в хранилище из файла
+ ///
+ /// Путь и имя файла
+ /// true - загрузка прошла успешно, false - ошибка при загрузке данных
+ public void LoadData(string filename)
{
- CollectionType.Massive => new MassiveGenericObjects(),
- CollectionType.List => new ListGenericObjects(),
- _ => null,
- };
+ if (!File.Exists(filename))
+ {
+ throw new FileNotFoundException("Файл не существует");
+ }
+
+ using (StreamReader sr = new(filename))
+ {
+ string str = sr.ReadLine();
+ if (str == null || str.Length == 0)
+ {
+ throw new FileFormatException("В файле нет данных");
+ }
+
+ if (!str.Equals(_collectionKey))
+ {
+ throw new FileFormatException("В файле неверные данные");
+ }
+ _storages.Clear();
+
+ while (!sr.EndOfStream)
+ {
+ string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
+ if (record.Length != 4)
+ {
+ continue;
+ }
+
+ CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
+ ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType);
+ if (collection == null)
+ {
+ throw new InvalidOperationException("Не удалось создать коллекцию");
+ }
+
+ collection.MaxCount = Convert.ToInt32(record[2]);
+
+ string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
+ foreach (string elem in set)
+ {
+ if (elem?.CreateDrawningCommonLiner() is T airplane)
+ {
+ try
+ {
+ if (collection.Insert(airplane) == -1)
+ throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
+ }
+ catch (CollectionOverflowException ex)
+ {
+ throw new OverflowException("Коллекция переполнена", ex);
+ }
+ }
+ }
+ _storages.Add(record[0], collection);
+ }
+ }
+ }
+
+ ///
+ /// Создание коллекции по типу
+ ///
+ ///
+ ///
+ private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType)
+ {
+ return collectionType switch
+ {
+ CollectionType.Massive => new MassiveGenericObjects(),
+ CollectionType.List => new ListGenericObjects(),
+ _ => null,
+ };
+ }
}
-}
\ No newline at end of file
+}
diff --git a/ProjectLiner/ProjectLiner/Entities/EntityLiner.cs b/ProjectLiner/ProjectLiner/Entities/EntityLiner.cs
index 0b44be7..cb1a862 100644
--- a/ProjectLiner/ProjectLiner/Entities/EntityLiner.cs
+++ b/ProjectLiner/ProjectLiner/Entities/EntityLiner.cs
@@ -77,5 +77,4 @@ public class EntityLiner: EntityCommonLiner
Color.FromName(strs[3]), Color.FromName(strs[4]),
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
}
-
}
\ No newline at end of file
diff --git a/ProjectLiner/ProjectLiner/Exceptions/CollectionOverflowException.cs b/ProjectLiner/ProjectLiner/Exceptions/CollectionOverflowException.cs
new file mode 100644
index 0000000..bab1071
--- /dev/null
+++ b/ProjectLiner/ProjectLiner/Exceptions/CollectionOverflowException.cs
@@ -0,0 +1,20 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectLiner.Exceptions;
+
+///
+/// Класс, описывающий ошибку переполнения коллекции
+///
+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) { }
+}
\ No newline at end of file
diff --git a/ProjectLiner/ProjectLiner/Exceptions/ObjectNotFoundException.cs b/ProjectLiner/ProjectLiner/Exceptions/ObjectNotFoundException.cs
new file mode 100644
index 0000000..6462346
--- /dev/null
+++ b/ProjectLiner/ProjectLiner/Exceptions/ObjectNotFoundException.cs
@@ -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 ProjectLiner.Exceptions;
+
+///
+/// Класс, описывающий ошибку, что по указанной позиции нет элемента
+///
+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) { }
+}
diff --git a/ProjectLiner/ProjectLiner/Exceptions/PositionOutOfCollectionException.cs b/ProjectLiner/ProjectLiner/Exceptions/PositionOutOfCollectionException.cs
new file mode 100644
index 0000000..83917a5
--- /dev/null
+++ b/ProjectLiner/ProjectLiner/Exceptions/PositionOutOfCollectionException.cs
@@ -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 ProjectLiner.Exceptions;
+
+///
+/// Класс, описывающий ошибку выхода за границы коллекции
+///
+[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) { }
+}
\ No newline at end of file
diff --git a/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs b/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs
index ad3a8cc..eb6b44c 100644
--- a/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs
+++ b/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs
@@ -75,7 +75,7 @@
// buttonCreateCompany
//
buttonCreateCompany.Font = new Font("Segoe UI", 9.75F, FontStyle.Regular, GraphicsUnit.Point);
- buttonCreateCompany.Location = new Point(8, 520);
+ buttonCreateCompany.Location = new Point(7, 495);
buttonCreateCompany.Margin = new Padding(5);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(257, 38);
@@ -96,13 +96,13 @@
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 43);
panelStorage.Name = "panelStorage";
- panelStorage.Size = new Size(266, 405);
+ panelStorage.Size = new Size(266, 370);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
//
buttonCollectionDel.Font = new Font("Segoe UI", 9.75F, FontStyle.Regular, GraphicsUnit.Point);
- buttonCollectionDel.Location = new Point(5, 348);
+ buttonCollectionDel.Location = new Point(3, 314);
buttonCollectionDel.Margin = new Padding(5);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(257, 38);
@@ -180,7 +180,7 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
- comboBoxSelectorCompany.Location = new Point(20, 458);
+ comboBoxSelectorCompany.Location = new Point(23, 419);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(242, 49);
comboBoxSelectorCompany.TabIndex = 0;
@@ -249,7 +249,7 @@
button3.TabIndex = 4;
button3.Text = "Удаление Лайнера";
button3.UseVisualStyleBackColor = true;
- button3.Click += ButtonRemoveLiner_Click;
+ button3.Click += ButtonRemoveCommonLiner_Click;
//
// button4
//
diff --git a/ProjectLiner/ProjectLiner/FormLinerCollection.cs b/ProjectLiner/ProjectLiner/FormLinerCollection.cs
index 8208c72..a96fe40 100644
--- a/ProjectLiner/ProjectLiner/FormLinerCollection.cs
+++ b/ProjectLiner/ProjectLiner/FormLinerCollection.cs
@@ -1,266 +1,328 @@
-
+using Microsoft.Extensions.Logging;
using ProjectLiner.CollectionGenericObjects;
using ProjectLiner.Drawnings;
+using ProjectLiner.Exceptions;
+using ProjectLiner.CollectionGenericObjects;
+using ProjectLiner.Exceptions;
using System.Windows.Forms;
-namespace ProjectLiner;
-///
-/// Форма работы с компанией и ее коллекцией
-///
-public partial class FormLinerCollection : Form
+namespace ProjectLiner
{
///
- /// Хранилише коллекций
+ /// Форма работы с компанией и ее коллекцией
///
- private readonly StorageCollection _storageCollection;
- ///
- /// Компания
- ///
- private AbstractCompany? _company = null;
- ///
- /// Конструктор
- ///
- public FormLinerCollection()
+ public partial class FormLinerCollection : Form
{
- InitializeComponent();
- _storageCollection = new();
- }
- ///
- /// Выбор компании
- ///
- ///
- ///
- private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
- {
- panelCompanyTools.Enabled = false;
- }
- ///
- /// Добавление лайнера
- ///
- ///
- ///
- private void ButtonAddCommonLiner_Click(object sender, EventArgs e)
- {
- FormLinerConfig form = new();
- form.Show();
- form.AddEvent(SetLiner);
- }
+ ///
+ /// Хранилише коллекций
+ ///
+ private readonly StorageCollection _storageCollection;
- ///
- /// Добавление Лайнера в коллекцию
- ///
- ///
- private void SetLiner(DrawningCommonLiner liner)
- {
- if (_company == null || liner == null)
+ ///
+ /// Компания
+ ///
+ private AbstractCompany? _company = null;
+
+ ///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
+
+ ///
+ /// Конструктор
+ ///
+ public FormLinerCollection(ILogger logger)
{
- return;
+ InitializeComponent();
+ _storageCollection = new();
+ _logger = logger;
+ _logger.LogInformation("Форма загрузилась");
}
- if (_company + liner != -1)
+ ///
+ /// Выбор компании
+ ///
+ ///
+ ///
+ private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
- MessageBox.Show("Объект добавлен");
+ panelCompanyTools.Enabled = false;
+ }
+
+ ///
+ /// Добавление самолета
+ ///
+ ///
+ ///
+ private void ButtonAddCommonLiner_Click(object sender, EventArgs e)
+ {
+ FormLinerConfig form = new();
+ form.Show();
+ form.AddEvent(SetLiner);
+ }
+
+ ///
+ /// Добавление самолета в коллекцию
+ ///
+ ///
+ private void SetLiner(DrawningCommonLiner CommonLiner)
+ {
+ try
+ {
+ if (_company == null || CommonLiner == null)
+ {
+ return;
+ }
+
+ if (_company + CommonLiner != -1)
+ {
+ MessageBox.Show("Объект добавлен");
+ pictureBox.Image = _company.Show();
+ _logger.LogInformation("Добавлен объект: {0}", CommonLiner.GetDataForSave());
+ }
+ }
+ catch (CollectionOverflowException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
+ }
+
+ ///
+ /// Удаление объекта
+ ///
+ ///
+ ///
+ private void ButtonRemoveCommonLiner_Click(object sender, EventArgs e)
+ {
+ if (string.IsNullOrEmpty(maskedTextBox1.Text) || _company == null)
+ {
+ return;
+ }
+
+ if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
+ {
+ return;
+ }
+
+ try
+ {
+ int pos = Convert.ToInt32(maskedTextBox1.Text);
+ if (_company - pos != null)
+ {
+ MessageBox.Show("Объект удален");
+ pictureBox.Image = _company.Show();
+ _logger.LogInformation("Удалён объект по позиции {0}", pos);
+ }
+ }
+ catch (PositionOutOfCollectionException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
+ catch (ObjectNotFoundException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
+ }
+
+ ///
+ /// Передача объекта в другую форму
+ ///
+ ///
+ ///
+ private void ButtonGoToCheck_Click(object sender, EventArgs e)
+ {
+ if (_company == null)
+ {
+ return;
+ }
+
+ try
+ {
+ DrawningCommonLiner? plane = null;
+ int counter = 100;
+ while (plane == null)
+ {
+ plane = _company.GetRandomObject();
+ counter--;
+ if (counter <= 0)
+ {
+ break;
+ }
+ }
+
+ if (plane == null)
+ {
+ return;
+ }
+
+ FormLiner form = new()
+ {
+ SetLiner = plane
+ };
+ form.ShowDialog();
+ }
+ catch (ObjectNotFoundException)
+ {
+ _logger.LogError("Ошибка при передаче объекта на FormLiner");
+ }
+ }
+
+ ///
+ /// Перерисовка коллекции
+ ///
+ ///
+ ///
+ private void ButtonRefresh_Click(object sender, EventArgs e)
+ {
+ if (_company == null)
+ {
+ return;
+ }
+
pictureBox.Image = _company.Show();
}
- else
- {
- MessageBox.Show("Не удалось добавить объект");
- }
- }
- ///
- /// Удаление объекта
- ///
- ///
- ///
- private void ButtonRemoveLiner_Click(object sender, EventArgs e)
- {
- if (string.IsNullOrEmpty(maskedTextBoxPosition?.Text) || _company == null)
+ ///
+ /// Добавление коллекции
+ ///
+ ///
+ ///
+ private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
- return;
- }
- if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
- {
- return;
- }
- int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
- if (_company - pos != null)
- {
- MessageBox.Show("Объект удален");
- pictureBox.Image = _company.Show();
- }
- else
- {
- MessageBox.Show("Не удалось удалить объект");
- }
-
- }
- ///
- /// Передача объекта в другую форму
- ///
- ///
- ///
- private void ButtonGoToCheck_Click(object sender, EventArgs e)
- {
- if (_company == null)
- {
- return;
- }
- DrawningCommonLiner? liner = null;
- int counter = 100;
- while (liner == null)
- {
- liner = _company.GetRandomObject();
- counter--;
- if (counter <= 0) break;
- }
- if (liner == null)
- {
- return;
- }
- FormLiner form = new FormLiner();
- form.SetLiner = liner;
- form.ShowDialog();
- }
- ///
- /// Перерисовка коллекции
- ///
- ///
- ///
- private void ButtonRefresh_Click(object sender, EventArgs e)
- {
- if (_company == null)
- {
- return;
- }
-
- pictureBox.Image = _company.Show();
-
- }
- ///
- /// Добавление коллекции
- ///
- ///
- ///
- private void ButtonCollectionAdd_Click(object sender, EventArgs e)
- {
- if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
- {
- MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- CollectionType collectionType = CollectionType.None;
- if (radioButtonMassive.Checked)
- {
- collectionType = CollectionType.Massive;
- }
- else if (radioButtonList.Checked)
- {
- collectionType = CollectionType.List;
- }
- _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
- RerfreshListBoxItems();
- }
- ///
- /// Удаление коллекции
- ///
- ///
- ///
- private void ButtonCollectionDel_Click(object sender, EventArgs e)
- {
- if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
- {
- MessageBox.Show("Коллекция не выбрана");
- return;
- }
- if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
- {
- return;
- }
- _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
- RerfreshListBoxItems();
- }
- ///
- /// Обновление списка в listBoxCollection
- ///
- private void RerfreshListBoxItems()
- {
- listBoxCollection.Items.Clear();
- for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
- {
- string? colName = _storageCollection.Keys?[i];
- if (!string.IsNullOrEmpty(colName))
+ if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
- listBoxCollection.Items.Add(colName);
+ MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции");
+ return;
+ }
+
+ CollectionType collectionType = CollectionType.None;
+ if (radioButtonMassive.Checked)
+ collectionType = CollectionType.Massive;
+ else if (radioButtonList.Checked)
+ collectionType = CollectionType.List;
+
+ _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
+ RefreshListBoxItems();
+ _logger.LogInformation("Добавлена коллекция: {Collection} типа: {Type}", textBoxCollectionName.Text, collectionType);
+ }
+
+ ///
+ /// Удаление коллекции
+ ///
+ ///
+ ///
+ private void ButtonCollectionDel_Click(object sender, EventArgs e)
+ {
+ if (listBoxCollection.SelectedItems == null || listBoxCollection.SelectedIndex < 0)
+ {
+ MessageBox.Show("Коллекция не выбрана");
+ return;
+ }
+ if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
+ {
+ return;
+ }
+
+ _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
+ RefreshListBoxItems();
+ _logger.LogInformation("Коллекция удалена: {0}", textBoxCollectionName.Text);
+ }
+
+ ///
+ /// Обновление списка в listBoxCollection
+ ///
+ private void RefreshListBoxItems()
+ {
+ listBoxCollection.Items.Clear();
+ for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
+ {
+ string? colName = _storageCollection.Keys?[i];
+ if (!string.IsNullOrEmpty(colName))
+ listBoxCollection.Items.Add(colName);
}
}
- }
- ///
- /// Создание компании
- ///
- ///
- ///
- private void ButtonCreateCompany_Click(object sender, EventArgs e)
- {
- if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
- {
- MessageBox.Show("Коллекция не выбрана");
- return;
- }
- ICollectionGenericObjects? collection =
- _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
- if (collection == null)
- {
- MessageBox.Show("Коллекция не проинициализирована");
- return;
- }
- switch (comboBoxSelectorCompany.Text)
- {
- case "Хранилище":
- _company = new LinerSharingService(pictureBox.Width, pictureBox.Height, collection);
- break;
- }
- panelCompanyTools.Enabled = true;
- RerfreshListBoxItems();
- }
- ///
- /// Обработка нажатия "Сохранение"
- ///
- ///
- ///
- private void saveToolStripMenuItem_Click(object sender, EventArgs e)
- {
- if (saveFileDialog.ShowDialog() == DialogResult.OK)
+ ///
+ /// Создание компании
+ ///
+ ///
+ ///
+ private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
- if (_storageCollection.SaveData(saveFileDialog.FileName))
+ if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
- MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ MessageBox.Show("Коллекция не выбрана");
+ return;
}
- else
+
+ ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
+ if (collection == null)
{
- MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show("Коллекция не проинициализирована");
+ return;
+ }
+
+ switch (comboBoxSelectorCompany.Text)
+ {
+ case "Хранилище":
+ _company = new LinerSharingService(pictureBox.Width, pictureBox.Height, collection);
+ _logger.LogInformation("Создна компания типа {Company}, коллекция: {Collection}", comboBoxSelectorCompany.Text, textBoxCollectionName.Text);
+ _logger.LogInformation("Создана компания на коллекции: {Collection}", textBoxCollectionName.Text);
+ break;
+ }
+
+ panelCompanyTools.Enabled = true;
+ RefreshListBoxItems();
+ }
+
+ ///
+ /// Обработка нажатия "Сохранение"
+ ///
+ ///
+ ///
+ private void saveToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ if (saveFileDialog.ShowDialog() == DialogResult.OK)
+ {
+ try
+ {
+ _storageCollection.SaveData(saveFileDialog.FileName);
+ MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
+ }
+ catch (Exception ex)
+ {
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
}
}
- }
- ///
- /// Обработка нажатия "Загрузка"
- ///
- ///
- ///
- private void loadToolStripMenuItem_Click(object sender, EventArgs e)
- {
- if (openFileDialog.ShowDialog() == DialogResult.OK)
+ ///
+ /// Обработка нажатия "Загрузка"
+ ///
+ ///
+ ///
+ private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
- if (_storageCollection.LoadData(openFileDialog.FileName))
+ if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
- RerfreshListBoxItems();
- }
- else
- {
- MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ try
+ {
+ _storageCollection.LoadData(openFileDialog.FileName);
+ MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ RefreshListBoxItems();
+ _logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
+ }
+ catch (Exception ex)
+ {
+ MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
}
}
}
diff --git a/ProjectLiner/ProjectLiner/FormLinerCollection.resx b/ProjectLiner/ProjectLiner/FormLinerCollection.resx
index 1b18cc5..5982093 100644
--- a/ProjectLiner/ProjectLiner/FormLinerCollection.resx
+++ b/ProjectLiner/ProjectLiner/FormLinerCollection.resx
@@ -126,4 +126,7 @@
519, 17
+
+ 25
+
\ No newline at end of file
diff --git a/ProjectLiner/ProjectLiner/Program.cs b/ProjectLiner/ProjectLiner/Program.cs
index e3f64ca..68aced0 100644
--- a/ProjectLiner/ProjectLiner/Program.cs
+++ b/ProjectLiner/ProjectLiner/Program.cs
@@ -1,3 +1,8 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Serilog;
+
namespace ProjectLiner
{
internal static class Program
@@ -10,8 +15,36 @@ namespace ProjectLiner
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
+
ApplicationConfiguration.Initialize();
- Application.Run(new FormLinerCollection());
+ ServiceCollection services = new();
+ ConfigureServices(services);
+ using ServiceProvider serviceProvider = services.BuildServiceProvider();
+ Application.Run(serviceProvider.GetRequiredService());
+ }
+
+ ///
+ /// Êîíôèãóðàöèÿ ñåðâèñà DI
+ ///
+ ///
+ 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()
+ .AddLogging(option =>
+ {
+ option.SetMinimumLevel(LogLevel.Information);
+ option.AddSerilog(new LoggerConfiguration()
+ .ReadFrom.Configuration(new ConfigurationBuilder()
+ .AddJsonFile($"{pathNeed}serilog.json")
+ .Build())
+ .CreateLogger());
+ });
}
}
}
\ No newline at end of file
diff --git a/ProjectLiner/ProjectLiner/ProjectLiner.csproj b/ProjectLiner/ProjectLiner/ProjectLiner.csproj
index 244387d..5e663e8 100644
--- a/ProjectLiner/ProjectLiner/ProjectLiner.csproj
+++ b/ProjectLiner/ProjectLiner/ProjectLiner.csproj
@@ -8,6 +8,15 @@
enable
+
+
+
+
+
+
+
+
+
True
@@ -23,4 +32,10 @@
+
+
+ Always
+
+
+
\ No newline at end of file
diff --git a/ProjectLiner/ProjectLiner/serilog.json b/ProjectLiner/ProjectLiner/serilog.json
new file mode 100644
index 0000000..21a527e
--- /dev/null
+++ b/ProjectLiner/ProjectLiner/serilog.json
@@ -0,0 +1,19 @@
+{
+ "Serilog": {
+ "Using": [
+ "Serilog.Sinks.File"
+ ],
+ "MinimumLevel": "Debug",
+ "WriteTo": [
+ {
+ "Name": "File",
+ "Args": {
+ "path": "log.log"
+ }
+ }
+ ],
+ "Properties": {
+ "Application": "Sample"
+ }
+ }
+}
\ No newline at end of file