Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fa6661bfce | |||
| 6cc0b436dc | |||
| 2c7ad4fcb6 | |||
| 86aefff199 | |||
| 2365620cf6 | |||
| 21741e196c |
@@ -3,6 +3,7 @@ using ProjectAccordionBus.MovementStrategy;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Numerics;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@@ -20,14 +21,14 @@ public abstract class AbstractCompany
|
||||
|
||||
protected ICollectionGenericObjects<DrawningBus?> _collection = null;
|
||||
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _placeSizeHeight / 2 * 3);
|
||||
|
||||
public AbstractCompany(int picWidth, int picHeigth, ICollectionGenericObjects<DrawningBus> collection)
|
||||
{
|
||||
_pictureWidth = picWidth;
|
||||
_pictureHeight = picHeigth;
|
||||
_collection = collection;
|
||||
_collection.SetMaxCount = GetMaxCount;
|
||||
_collection.MaxCount = GetMaxCount;
|
||||
}
|
||||
|
||||
public static int operator +(AbstractCompany company, DrawningBus bus)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -21,14 +22,14 @@ public interface ICollectionGenericObjects<T>
|
||||
/// <summary>
|
||||
/// Установка максимального кол-ва объектов
|
||||
/// </summary>
|
||||
int SetMaxCount { set; }
|
||||
int MaxCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Добавление объекта в коллецию
|
||||
/// </summary>
|
||||
/// <param name="obj"></param>
|
||||
/// <returns></returns>
|
||||
int Insert(T obj);
|
||||
int Insert(T obj);
|
||||
|
||||
/// <summary>
|
||||
/// Добавление объекта в коллекцию
|
||||
@@ -50,5 +51,16 @@ public interface ICollectionGenericObjects<T>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <returns>Объект</returns>
|
||||
T? Get(int position);
|
||||
|
||||
/// <summary>
|
||||
/// Получение типа коллекции
|
||||
/// </summary>
|
||||
CollectionType GetCollectionType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Получение объектов коллекции по одному
|
||||
/// </summary>
|
||||
/// <returns>Поэлементый вывод элементов коллекции</returns>
|
||||
IEnumerable<T?> GetItems();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using ProjectAccordionBus.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -12,11 +13,21 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
private readonly List<T> _collection;
|
||||
|
||||
private int _maxCount;
|
||||
public int MaxCount => _maxCount;
|
||||
public int MaxCount {
|
||||
get => _maxCount;
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
{
|
||||
_maxCount = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int Count => _collection.Count;
|
||||
|
||||
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
public ListGenericObjects()
|
||||
{
|
||||
@@ -25,41 +36,38 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T Get(int position)
|
||||
{
|
||||
if (position < 0 || position >= _collection.Count || _collection == null || _collection.Count == 0) return null;
|
||||
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
if (Count == _maxCount)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return _collection.Count;
|
||||
return Count;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (Count == _maxCount || position < 0 || position > Count)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
if (_collection == null || position < 0 || position >= _collection.Count) return null;
|
||||
|
||||
T? obj = _collection[position];
|
||||
_collection[position] = null;
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
T obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return obj;
|
||||
}
|
||||
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Count; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using ProjectAccordionBus.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -20,8 +21,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public int Count => _collection.Length;
|
||||
|
||||
public int SetMaxCount
|
||||
public int MaxCount
|
||||
{
|
||||
get
|
||||
{
|
||||
return _collection.Length;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
@@ -38,6 +43,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@@ -49,16 +56,34 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
int index = 0;
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
int index = position + 1;
|
||||
while (index < _collection.Length)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
@@ -66,56 +91,36 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
}
|
||||
index++;
|
||||
++index;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
|
||||
if (position >= _collection.Length || position < 0)
|
||||
return -1;
|
||||
|
||||
|
||||
if (_collection[position] != null)
|
||||
index = position - 1;
|
||||
while (index >= 0)
|
||||
{
|
||||
// проверка, что после вставляемого элемента в массиве есть пустой элемент
|
||||
int nullIndex = -1;
|
||||
for (int i = position + 1; i < Count; i++)
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
nullIndex = i;
|
||||
break;
|
||||
}
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
}
|
||||
// Если пустого элемента нет, то выходим
|
||||
if (nullIndex < 0)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
// сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
|
||||
int j = nullIndex - 1;
|
||||
while (j >= position)
|
||||
{
|
||||
_collection[j + 1] = _collection[j];
|
||||
j--;
|
||||
}
|
||||
}
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
--index;
|
||||
}
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
T? temp = _collection[position];
|
||||
_collection[position] = null;
|
||||
return temp;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Length; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
using System;
|
||||
using ProjectAccordionBus.Drawnings;
|
||||
using ProjectAccordionBus.CollectionGenericObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using ProjectAccordionBus.Exceptions;
|
||||
|
||||
namespace ProjectAccordionBus.CollectionGenericObjects;
|
||||
|
||||
public class StorageCollection<T>
|
||||
where T : class
|
||||
where T : DrawningBus
|
||||
{
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
@@ -18,7 +21,21 @@ public class StorageCollection<T>
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
public List<string> Keys => _storages.Keys.ToList();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionsStorage";
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly string _separatorItems = ";";
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
@@ -34,17 +51,19 @@ public class StorageCollection<T>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
|
||||
// TODO Прописать логику для добавления
|
||||
if (_storages.ContainsKey(name) || name == "") return;
|
||||
|
||||
if (collectionType == CollectionType.Massive)
|
||||
if (name == null || _storages.ContainsKey(name))
|
||||
return;
|
||||
switch (collectionType)
|
||||
{
|
||||
_storages[name] = new MassiveGenericObjects<T>();
|
||||
}
|
||||
else
|
||||
{
|
||||
_storages[name] = new ListGenericObjects<T>();
|
||||
case CollectionType.None:
|
||||
return;
|
||||
case CollectionType.Massive:
|
||||
_storages[name] = new MassiveGenericObjects<T>();
|
||||
return;
|
||||
case CollectionType.List:
|
||||
_storages[name] = new ListGenericObjects<T>();
|
||||
return;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@@ -53,8 +72,8 @@ public class StorageCollection<T>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
// TODO Прописать логику для удаления коллекции
|
||||
_storages.Remove(name);
|
||||
if (_storages.ContainsKey(name))
|
||||
_storages.Remove(name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -66,7 +85,6 @@ public class StorageCollection<T>
|
||||
{
|
||||
get
|
||||
{
|
||||
// TODO Продумать логику получения объекта
|
||||
if (name == "")
|
||||
{
|
||||
return null;
|
||||
@@ -75,4 +93,119 @@ public class StorageCollection<T>
|
||||
}
|
||||
}
|
||||
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
using (StreamWriter writer = new(filename))
|
||||
{
|
||||
writer.Write(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
writer.Write(Environment.NewLine);
|
||||
// не сохраняем пустые коллекции
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
writer.Write(value.Key);
|
||||
writer.Write(_separatorForKeyValue);
|
||||
writer.Write(value.Value.GetCollectionType);
|
||||
writer.Write(_separatorForKeyValue);
|
||||
writer.Write(value.Value.MaxCount);
|
||||
writer.Write(_separatorForKeyValue);
|
||||
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
if (string.IsNullOrEmpty(data))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
writer.Write(data);
|
||||
writer.Write(_separatorItems);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new FileNotFoundException($"{filename} не существует");
|
||||
}
|
||||
using (StreamReader reader = new(filename))
|
||||
{
|
||||
string line = reader.ReadLine();
|
||||
if (line == null || line.Length == 0)
|
||||
{
|
||||
throw new IOException("Файл не подходит");
|
||||
}
|
||||
if (!line.Equals(_collectionKey))
|
||||
{
|
||||
|
||||
throw new IOException("В файле неверные данные");
|
||||
}
|
||||
_storages.Clear();
|
||||
while ((line = reader.ReadLine()) != null)
|
||||
{
|
||||
string[] record = line.Split(_separatorForKeyValue,
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
throw new Exception("Не удалось создать коллекцию");
|
||||
}
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
string[] set = record[3].Split(_separatorItems,
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningBus() is T armoredCar)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(armoredCar) == -1)
|
||||
{
|
||||
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new Exception("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>?
|
||||
CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
return collectionType switch
|
||||
{
|
||||
CollectionType.Massive => new MassiveGenericObjects<T>(),
|
||||
CollectionType.List => new ListGenericObjects<T>(),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,14 @@ public class DrawningAccordionBus : DrawningBus
|
||||
EntityBus = new EntityAccordionBus(speed, weight, bodyColor, additionalColor, compartment, entrance, windows);
|
||||
}
|
||||
|
||||
public DrawningAccordionBus(EntityBus? entityBus)
|
||||
{
|
||||
if (entityBus != null)
|
||||
{
|
||||
EntityBus = entityBus;
|
||||
}
|
||||
}
|
||||
|
||||
public override void DrawTransport(Graphics g)
|
||||
{
|
||||
if (EntityBus == null || EntityBus is not EntityAccordionBus accordionBus || !_startPosX.HasValue || !_startPosY.HasValue)
|
||||
@@ -28,35 +36,38 @@ public class DrawningAccordionBus : DrawningBus
|
||||
|
||||
Brush brushBlue = new SolidBrush(Color.Blue);
|
||||
// отсек
|
||||
g.FillRectangle(additionalBrush, _startPosX.Value + 60, _startPosY.Value, 50, 30);
|
||||
g.FillRectangle(additionalBrush, _startPosX.Value + 50, _startPosY.Value + 5, 10, 20);
|
||||
|
||||
g.DrawRectangle(pen, _startPosX.Value + 60, _startPosY.Value, 50, 30);
|
||||
g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 5, 10, 20);
|
||||
|
||||
// колеса
|
||||
g.FillEllipse(additionalBrush, _startPosX.Value + 65, _startPosY.Value + 25, 10, 10);
|
||||
g.FillEllipse(additionalBrush, _startPosX.Value + 95, _startPosY.Value + 25, 10, 10);
|
||||
|
||||
g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 25, 10, 10);
|
||||
g.DrawEllipse(pen, _startPosX.Value + 95, _startPosY.Value + 25, 10, 10);
|
||||
|
||||
if (accordionBus.Entrance)
|
||||
if (accordionBus.Compartment)
|
||||
{
|
||||
g.FillRectangle(additionalBrush, _startPosX.Value + 78, _startPosY.Value + 10, 10, 20);
|
||||
g.FillRectangle(additionalBrush, _startPosX.Value + 60, _startPosY.Value, 50, 30);
|
||||
g.FillRectangle(additionalBrush, _startPosX.Value + 50, _startPosY.Value + 5, 10, 20);
|
||||
|
||||
g.DrawRectangle(pen, _startPosX.Value + 78, _startPosY.Value + 10, 10, 20);
|
||||
}
|
||||
g.DrawRectangle(pen, _startPosX.Value + 60, _startPosY.Value, 50, 30);
|
||||
g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 5, 10, 20);
|
||||
|
||||
if (accordionBus.Windows)
|
||||
{
|
||||
g.FillEllipse(brushBlue, _startPosX.Value + 65, _startPosY.Value + 5, 5, 10);
|
||||
g.FillEllipse(brushBlue, _startPosX.Value + 100, _startPosY.Value + 5, 5, 10);
|
||||
g.FillEllipse(brushBlue, _startPosX.Value + 90, _startPosY.Value + 5, 5, 10);
|
||||
// колеса
|
||||
g.FillEllipse(additionalBrush, _startPosX.Value + 65, _startPosY.Value + 25, 10, 10);
|
||||
g.FillEllipse(additionalBrush, _startPosX.Value + 95, _startPosY.Value + 25, 10, 10);
|
||||
|
||||
g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 5, 5, 10);
|
||||
g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 5, 5, 10);
|
||||
g.DrawEllipse(pen, _startPosX.Value + 90, _startPosY.Value + 5, 5, 10);
|
||||
g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 25, 10, 10);
|
||||
g.DrawEllipse(pen, _startPosX.Value + 95, _startPosY.Value + 25, 10, 10);
|
||||
|
||||
if (accordionBus.Entrance)
|
||||
{
|
||||
g.FillRectangle(additionalBrush, _startPosX.Value + 78, _startPosY.Value + 10, 10, 20);
|
||||
|
||||
g.DrawRectangle(pen, _startPosX.Value + 78, _startPosY.Value + 10, 10, 20);
|
||||
}
|
||||
|
||||
if (accordionBus.Windows)
|
||||
{
|
||||
g.FillEllipse(brushBlue, _startPosX.Value + 65, _startPosY.Value + 5, 5, 10);
|
||||
g.FillEllipse(brushBlue, _startPosX.Value + 100, _startPosY.Value + 5, 5, 10);
|
||||
g.FillEllipse(brushBlue, _startPosX.Value + 90, _startPosY.Value + 5, 5, 10);
|
||||
|
||||
g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 5, 5, 10);
|
||||
g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 5, 5, 10);
|
||||
g.DrawEllipse(pen, _startPosX.Value + 90, _startPosY.Value + 5, 5, 10);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@ public class DrawningBus
|
||||
public int GetHight => _drawningBusHeight;
|
||||
|
||||
// Пустой конструктор
|
||||
private DrawningBus()
|
||||
public DrawningBus()
|
||||
{
|
||||
_pictureWidth = null;
|
||||
_pictureHeight = null;
|
||||
@@ -85,6 +85,14 @@ public class DrawningBus
|
||||
_drawningBusHeight = drawningBusHeight;
|
||||
}
|
||||
|
||||
public DrawningBus(EntityBus? entityBus)
|
||||
{
|
||||
if (entityBus != null)
|
||||
{
|
||||
EntityBus = entityBus;
|
||||
}
|
||||
}
|
||||
|
||||
public bool SetPictureSize(int width, int height)
|
||||
{
|
||||
if (_drawningBusWidth <= width && _drawningBusHeight <= height)
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using ProjectAccordionBus.Entities;
|
||||
|
||||
namespace ProjectAccordionBus.Drawnings;
|
||||
|
||||
public static class ExtentionDrawningBus
|
||||
{
|
||||
private static readonly string _separatorForObject = ":";
|
||||
|
||||
/// <summary>
|
||||
/// Создание объекта из строки
|
||||
/// </summary>
|
||||
/// <param name="info">Строка с данными для создания объекта</param>
|
||||
/// <returns>Объект</returns>
|
||||
public static DrawningBus? CreateDrawningBus(this string info)
|
||||
{
|
||||
string[] strs = info.Split(_separatorForObject);
|
||||
EntityBus? bus = EntityAccordionBus.CreateEntityAccordionBus(strs);
|
||||
if (bus != null)
|
||||
{
|
||||
return new DrawningAccordionBus(bus);
|
||||
}
|
||||
|
||||
bus = EntityBus.CreateEntityBus(strs);
|
||||
if (bus != null)
|
||||
{
|
||||
return new DrawningBus(bus);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение данных для сохранения в файл
|
||||
/// </summary>
|
||||
/// <param name="drawningBus">Сохраняемый объект</param>
|
||||
/// <returns>Строка с данными по объекту</returns>
|
||||
public static string GetDataForSave(this DrawningBus drawningBus)
|
||||
{
|
||||
string[]? array = drawningBus?.EntityBus?.GetStringRepresentation();
|
||||
|
||||
if (array == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return string.Join(_separatorForObject, array);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static System.Reflection.Metadata.BlobBuilder;
|
||||
|
||||
namespace ProjectAccordionBus.Entities;
|
||||
|
||||
@@ -34,4 +36,20 @@ public class EntityAccordionBus : EntityBus
|
||||
Windows = windows;
|
||||
}
|
||||
|
||||
public override string[] GetStringRepresentation()
|
||||
{
|
||||
return new[] { nameof(EntityAccordionBus), Speed.ToString(), Weight.ToString(), BodyColor.Name,
|
||||
AdditionalColor.Name, Compartment.ToString(), Entrance.ToString(), Windows.ToString() };
|
||||
}
|
||||
|
||||
public static EntityAccordionBus? CreateEntityAccordionBus(string[] strs)
|
||||
{
|
||||
if (strs.Length != 8 || strs[0] != nameof(EntityAccordionBus))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new EntityAccordionBus(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]),
|
||||
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,4 +31,25 @@ public class EntityBus
|
||||
Weight = weight;
|
||||
BodyColor = bodyColor;
|
||||
}
|
||||
|
||||
public virtual string[] GetStringRepresentation()
|
||||
{
|
||||
return new[] { nameof(EntityBus), Speed.ToString(), Weight.ToString(), BodyColor.Name};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание объекта из массива строк
|
||||
/// </summary>
|
||||
/// <param name="strs"></param>
|
||||
/// <returns></returns>
|
||||
public static EntityBus? CreateEntityBus(string[] strs)
|
||||
{
|
||||
if (strs.Length != 4 || strs[0] != nameof(EntityBus))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new EntityBus(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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 ProjectAccordionBus.Exceptions;
|
||||
|
||||
[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,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectAccordionBus.Exceptions;
|
||||
|
||||
[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,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectAccordionBus.Exceptions;
|
||||
|
||||
[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) { }
|
||||
}
|
||||
@@ -46,10 +46,17 @@
|
||||
comboBoxSelectorCompany = new ComboBox();
|
||||
labelCollectionName = new Label();
|
||||
pictureBox = new PictureBox();
|
||||
menuStrip = new MenuStrip();
|
||||
файлToolStripMenuItem = new ToolStripMenuItem();
|
||||
saveToolStripMenuItem = new ToolStripMenuItem();
|
||||
loadToolStripMenuItem = new ToolStripMenuItem();
|
||||
saveFileDialog = new SaveFileDialog();
|
||||
openFileDialog = new OpenFileDialog();
|
||||
groupBoxTools.SuspendLayout();
|
||||
panelCompanyTools.SuspendLayout();
|
||||
panelStorage.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
|
||||
menuStrip.SuspendLayout();
|
||||
SuspendLayout();
|
||||
//
|
||||
// groupBoxTools
|
||||
@@ -57,9 +64,9 @@
|
||||
groupBoxTools.Controls.Add(panelCompanyTools);
|
||||
groupBoxTools.Controls.Add(panelStorage);
|
||||
groupBoxTools.Dock = DockStyle.Right;
|
||||
groupBoxTools.Location = new Point(625, 0);
|
||||
groupBoxTools.Location = new Point(625, 24);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Size = new Size(175, 510);
|
||||
groupBoxTools.Size = new Size(175, 511);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
groupBoxTools.Text = "Инструменты";
|
||||
@@ -73,7 +80,7 @@
|
||||
panelCompanyTools.Controls.Add(buttonAddBus);
|
||||
panelCompanyTools.Dock = DockStyle.Bottom;
|
||||
panelCompanyTools.Enabled = false;
|
||||
panelCompanyTools.Location = new Point(3, 316);
|
||||
panelCompanyTools.Location = new Point(3, 317);
|
||||
panelCompanyTools.Name = "panelCompanyTools";
|
||||
panelCompanyTools.Size = new Size(169, 191);
|
||||
panelCompanyTools.TabIndex = 10;
|
||||
@@ -244,19 +251,62 @@
|
||||
// pictureBox
|
||||
//
|
||||
pictureBox.Dock = DockStyle.Fill;
|
||||
pictureBox.Location = new Point(0, 0);
|
||||
pictureBox.Location = new Point(0, 24);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(625, 510);
|
||||
pictureBox.Size = new Size(625, 511);
|
||||
pictureBox.TabIndex = 4;
|
||||
pictureBox.TabStop = false;
|
||||
//
|
||||
// menuStrip
|
||||
//
|
||||
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
|
||||
menuStrip.Location = new Point(0, 0);
|
||||
menuStrip.Name = "menuStrip";
|
||||
menuStrip.Size = new Size(800, 24);
|
||||
menuStrip.TabIndex = 5;
|
||||
menuStrip.Text = "menuStrip";
|
||||
//
|
||||
// файлToolStripMenuItem
|
||||
//
|
||||
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
|
||||
файлToolStripMenuItem.Name = "файлToolStripMenuItem";
|
||||
файлToolStripMenuItem.Size = new Size(48, 20);
|
||||
файлToolStripMenuItem.Text = "Файл";
|
||||
//
|
||||
// saveToolStripMenuItem
|
||||
//
|
||||
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
|
||||
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
|
||||
saveToolStripMenuItem.Size = new Size(181, 22);
|
||||
saveToolStripMenuItem.Text = "Сохранение";
|
||||
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
|
||||
//
|
||||
// loadToolStripMenuItem
|
||||
//
|
||||
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
|
||||
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
|
||||
loadToolStripMenuItem.Size = new Size(181, 22);
|
||||
loadToolStripMenuItem.Text = "Загрузка";
|
||||
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
|
||||
//
|
||||
// saveFileDialog
|
||||
//
|
||||
saveFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// openFileDialog
|
||||
//
|
||||
openFileDialog.FileName = "openFileDialog";
|
||||
openFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// FormBusCollection
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(800, 510);
|
||||
ClientSize = new Size(800, 535);
|
||||
Controls.Add(pictureBox);
|
||||
Controls.Add(groupBoxTools);
|
||||
Controls.Add(menuStrip);
|
||||
MainMenuStrip = menuStrip;
|
||||
Name = "FormBusCollection";
|
||||
Text = "Коллекция автобусов";
|
||||
groupBoxTools.ResumeLayout(false);
|
||||
@@ -265,7 +315,10 @@
|
||||
panelStorage.ResumeLayout(false);
|
||||
panelStorage.PerformLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
|
||||
menuStrip.ResumeLayout(false);
|
||||
menuStrip.PerformLayout();
|
||||
ResumeLayout(false);
|
||||
PerformLayout();
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -288,5 +341,11 @@
|
||||
private Button buttonCollectionDel;
|
||||
private Button buttonCreateCompany;
|
||||
private Panel panelCompanyTools;
|
||||
private MenuStrip menuStrip;
|
||||
private ToolStripMenuItem файлToolStripMenuItem;
|
||||
private ToolStripMenuItem saveToolStripMenuItem;
|
||||
private ToolStripMenuItem loadToolStripMenuItem;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private OpenFileDialog openFileDialog;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using ProjectAccordionBus.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectAccordionBus.CollectionGenericObjects;
|
||||
using ProjectAccordionBus.Drawnings;
|
||||
using ProjectAccordionBus.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
@@ -27,20 +29,28 @@ public partial class FormBusCollection : Form
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormBusCollection()
|
||||
public FormBusCollection(ILogger<FormBusCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление улучшенного троллейбуса
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonAddAccordionBus_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAccordionBus));
|
||||
private void ButtonAddAccordionBus_Click(object sender, EventArgs e)
|
||||
{
|
||||
FormBusConfig form = new FormBusConfig();
|
||||
form.Show();
|
||||
form.AddEvent(SetBus);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание объекта класса-перемещения
|
||||
@@ -106,18 +116,24 @@ public partial class FormBusCollection : Form
|
||||
|
||||
private void SetBus(DrawningBus bus)
|
||||
{
|
||||
if (_company == null || bus == null) return;
|
||||
|
||||
bus.SetPictureSize(pictureBox.Width, pictureBox.Height);
|
||||
|
||||
if (_company + bus != -1)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
if (_company == null || bus == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (_company + bus != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Добавлен объект: {0}", bus.GetDataForSave());
|
||||
}
|
||||
|
||||
}
|
||||
else
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Объект не удалось добавить");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError($"Ошибка: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,37 +144,60 @@ public partial class FormBusCollection : Form
|
||||
return;
|
||||
}
|
||||
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int pos = Convert.ToInt32(maskedTextBox.Text);
|
||||
if (_company - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удалён");
|
||||
pictureBox.Image = _company.Show();
|
||||
if (_company - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Удален объект по позиции " + pos);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show($"Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void buttonGoToCheck_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null) return;
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
DrawningBus? bus = null;
|
||||
int counter = 100;
|
||||
while (bus == null || counter > 0)
|
||||
while (bus == null)
|
||||
{
|
||||
bus = _company.GetRandomObject();
|
||||
counter--;
|
||||
try
|
||||
{
|
||||
bus = _company.GetRandomObject();
|
||||
}
|
||||
catch (ObjectNotFoundException)
|
||||
{
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (bus == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (bus == null) return;
|
||||
|
||||
FormAccordionBus form = new()
|
||||
{
|
||||
SetBus = bus
|
||||
@@ -193,10 +232,12 @@ public partial class FormBusCollection : Form
|
||||
|
||||
private void buttonCollectionAdd_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
|
||||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning("Не заполненная коллекция");
|
||||
return;
|
||||
}
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
@@ -208,8 +249,8 @@ public partial class FormBusCollection : Form
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text,
|
||||
collectionType);
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}");
|
||||
RefreshListBoxItems();
|
||||
}
|
||||
|
||||
@@ -229,44 +270,83 @@ public partial class FormBusCollection : Form
|
||||
|
||||
private void buttonCollectionDel_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxCollection.SelectedItem == null) return;
|
||||
|
||||
if (MessageBox.Show("Вы действительно хотите удалить выбранный элемент?",
|
||||
"Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
RefreshListBoxItems();
|
||||
MessageBox.Show("Компания удалена");
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
_logger.LogWarning("Удаление невыбранной коллекции");
|
||||
return;
|
||||
}
|
||||
else
|
||||
string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить компанию");
|
||||
return;
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
_logger.LogInformation($"Удалена коллекция: {name}");
|
||||
RefreshListBoxItems();
|
||||
}
|
||||
|
||||
private void buttonCreateCompany_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxCollection.SelectedIndex < 0)
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Компания не выбрана");
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
_logger.LogWarning("Создание компании невыбранной коллекции");
|
||||
return;
|
||||
}
|
||||
|
||||
ICollectionGenericObjects<DrawningBus?> collection = _storageCollection[listBoxCollection.SelectedItem?.ToString() ?? string.Empty];
|
||||
ICollectionGenericObjects<DrawningBus>? collection =
|
||||
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Компания не инициализирована");
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
_logger.LogWarning("Не удалось инициализировать коллекцию");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (comboBoxSelectorCompany.Text)
|
||||
{
|
||||
case "Хранилище":
|
||||
_company = new BusSharingService(pictureBox.Width, pictureBox.Height, collection);
|
||||
_company = new BusSharingService(pictureBox.Width,
|
||||
pictureBox.Height, collection);
|
||||
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)
|
||||
{
|
||||
try
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
|
||||
RefreshListBoxItems();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,4 +117,13 @@
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>17, 17</value>
|
||||
</metadata>
|
||||
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>126, 17</value>
|
||||
</metadata>
|
||||
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>261, 17</value>
|
||||
</metadata>
|
||||
</root>
|
||||
@@ -1,17 +1,40 @@
|
||||
namespace ProjectAccordionBus
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectAccordionBus;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
internal static class Program
|
||||
/// <summary>
|
||||
/// The main entry point for the application.
|
||||
/// </summary>
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
/// <summary>
|
||||
/// The main entry point for the application.
|
||||
/// </summary>
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormBusCollection());
|
||||
}
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
|
||||
ServiceCollection services = new();
|
||||
ConfigureServices(services);
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
Application.Run(serviceProvider.GetRequiredService<FormBusCollection>());
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services
|
||||
.AddSingleton<FormBusCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
var config = new ConfigurationBuilder()
|
||||
.AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true)
|
||||
.Build();
|
||||
option.AddSerilog(Log.Logger = new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(config)
|
||||
.CreateLogger());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,20 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
|
||||
<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>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@@ -23,4 +37,13 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="nlog.config">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="serilogConfig.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
15
ProjectAccordionBus/ProjectAccordionBus/nlog.config
Normal file
15
ProjectAccordionBus/ProjectAccordionBus/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>
|
||||
20
ProjectAccordionBus/ProjectAccordionBus/serilogConfig.json
Normal file
20
ProjectAccordionBus/ProjectAccordionBus/serilogConfig.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Information",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "Logs/log_.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
}
|
||||
],
|
||||
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
|
||||
"Properties": {
|
||||
"Application": "Linkor"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user