Compare commits

..

7 Commits

Author SHA1 Message Date
Roman-Klemendeev
e25dcc5567 fix1 2024-05-26 22:35:13 +04:00
Roman-Klemendeev
c9ad7127f9 лаба 7
# Conflicts:
#	ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/ListGenericObjects.cs
#	ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/StorageCollection.cs
#	ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.Designer.cs
#	ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.cs
2024-05-26 22:15:39 +04:00
Roman-Klemendeev
6725a8cb3a 53
# Conflicts:
#	ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/ListGenericObjects.cs
#	ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/StorageCollection.cs
#	ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.Designer.cs
#	ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.cs
#	ProjectGasolineTanker/ProjectGasolineTanker/FormTankerConfig.cs
2024-05-26 22:13:37 +04:00
ddc2987b68 исправление 2024-05-26 22:08:31 +04:00
учёба
73e7ef53de лаба 6 2024-05-26 22:08:31 +04:00
Roman-Klemendeev
c603a8b8b0 fix 2024-05-26 22:06:31 +04:00
Roman-Klemendeev
0d79940c46 53
# Conflicts:
#	ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.Designer.cs
#	ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.cs
2024-05-26 22:02:03 +04:00
24 changed files with 1372 additions and 197 deletions

View File

@ -0,0 +1,8 @@
using ProjectGasolineTanker.Drawnings;
namespace ProjectGasolineTanker;
/// <summary>
/// Делегат передачи объекта класса-прорисовки
/// </summary>
/// <param name="car"></param>
public delegate void TankerDelegate(DrawningTanker car);

View File

@ -15,7 +15,7 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Размер места (высота) /// Размер места (высота)
/// </summary> /// </summary>
protected readonly int _placeSizeHeight = 80; protected readonly int _placeSizeHeight = 97;
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
@ -35,7 +35,7 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -48,7 +48,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.SetMaxCount = GetMaxCount; _collection.MaxCount = GetMaxCount;
} }
/// <summary> /// <summary>
@ -95,10 +95,15 @@ public abstract class AbstractCompany
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{ {
DrawningTanker? obj = _collection?.Get(i); DrawningTanker? obj = _collection?.Get(i);
obj?.DrawTransport(graphics); obj?.DrawTransport(graphics);
} }
catch (Exception) { }
}
return bitmap; return bitmap;
} }

View File

@ -17,8 +17,6 @@ public class CarPark : AbstractCompany
protected override void DrawBackground(Graphics g) protected override void DrawBackground(Graphics g)
{ {
Pen pen = new Pen(Color.Brown, 3); Pen pen = new Pen(Color.Brown, 3);
int offsetX = 10, offsetY = -12; int offsetX = 10, offsetY = -12;
int x = 1 + offsetX, y = _pictureHeight - _placeSizeHeight + offsetY; int x = 1 + offsetX, y = _pictureHeight - _placeSizeHeight + offsetY;
@ -48,9 +46,13 @@ public class CarPark : AbstractCompany
} }
int row = numRows - 1, col = numCols; int row = numRows - 1, col = numCols;
for (int i = 0; i < _collection?.Count; i++, col--) for (int i = 0; i < _collection?.Count; i++, col--)
{
try
{ {
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9); _collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9);
}
catch (Exception) { }
if (col == 1) if (col == 1)
{ {
col = numCols + 1; col = numCols + 1;

View File

@ -11,7 +11,7 @@ public interface ICollectionGenericObjects<T>
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int SetMaxCount { set; } int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
@ -41,4 +41,15 @@ public interface ICollectionGenericObjects<T>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>Объект</returns> /// <returns>Объект</returns>
T? Get(int position); T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
} }

View File

@ -1,4 +1,6 @@
 
using ProjectGasolineTanker.Exceptions;
namespace ProjectGasolineTanker.CollectionGenericObjects; namespace ProjectGasolineTanker.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T> public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
@ -7,7 +9,19 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
private int _maxCount; private int _maxCount;
public int Count => _collection.Count; public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } public int MaxCount
{
get => _maxCount;
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -19,30 +33,24 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position >= 0 && position < Count) if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
{
return _collection[position]; return _collection[position];
} }
else
{
return null;
}
}
public int Insert(T obj) public int Insert(T obj)
{ {
if (Count == _maxCount) { return -1; } if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position < 0 || position >= Count || Count == _maxCount) if (position < 0 || position >= Count)
{ throw new PositionOutOfCollectionException(position);
return -1;
} if (Count == _maxCount)
throw new CollectionOverflowException(Count);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
@ -50,9 +58,17 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T Remove(int position) public T Remove(int position)
{ {
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;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
} }

View File

@ -1,4 +1,6 @@
namespace ProjectGasolineTanker.CollectionGenericObjects; using ProjectGasolineTanker.Exceptions;
namespace ProjectGasolineTanker.CollectionGenericObjects;
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T> public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
@ -10,8 +12,12 @@ where T : class
public int Count => _collection.Length; public int Count => _collection.Length;
public int SetMaxCount public int MaxCount
{ {
get
{
return _collection.Length;
}
set set
{ {
if (value > 0) if (value > 0)
@ -28,6 +34,8 @@ where T : class
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -38,14 +46,11 @@ where T : class
public T? Get(int position) public T? Get(int position)
{ {
if (position >= 0 && position < Count) if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
{ if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position]; return _collection[position];
} }
return null;
}
public int Insert(T obj) public int Insert(T obj)
{ {
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
@ -56,14 +61,14 @@ where T : class
return i; return i;
} }
} }
return -1; throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return -1; throw new PositionOutOfCollectionException(position);
} }
if (_collection[position] == null) if (_collection[position] == null)
{ {
@ -88,21 +93,26 @@ where T : class
} }
} }
return -1; throw new CollectionOverflowException(Count);
} }
public T? Remove(int position) public T Remove(int position)
{ {
// проверка позиции
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return null; throw new PositionOutOfCollectionException(position);
} }
if (_collection[position] == null) throw new ObjectNotFoundException(position);
if (_collection[position] == null) return null; T obj = _collection[position];
T? temp = _collection[position];
_collection[position] = null; _collection[position] = null;
return temp; return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
} }
} }

View File

@ -1,7 +1,10 @@
 using ProjectGasolineTanker.Drawnings;
using ProjectGasolineTanker.Exceptions;
using System.Text;
namespace ProjectGasolineTanker.CollectionGenericObjects; namespace ProjectGasolineTanker.CollectionGenericObjects;
public class StorageCollection<T> public class StorageCollection<T>
where T : class where T : DrawningTanker
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
@ -13,6 +16,21 @@ public class StorageCollection<T>
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); 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>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -74,4 +92,124 @@ public class StorageCollection<T>
return null; return null;
} }
} }
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
using (StreamWriter sw = new StreamWriter(filename))
{
sw.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> kvpair in _storages)
{
// не сохраняем пустые коллекции
if (kvpair.Value.Count == 0)
continue;
sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
continue;
sb.Append(data);
sb.Append(_separatorItems);
}
sw.WriteLine(sb.ToString());
sb.Clear();
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str == null || str.Length == 0)
throw new Exception("В файле нет данных");
if (str != _collectionKey.ToString())
throw new Exception("В файле неверные данные");
_storages.Clear();
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
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?.CreateDrawningTanker() is T tanker)
{
try
{
if (collection.Insert(tanker) == -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,
};
}
} }

View File

@ -17,6 +17,14 @@ public class DrawningGasolineTanker : DrawningTanker
{ {
EntityTanker = new EntityGasolineTanker(speed, weight, bodyColor, additionalColor, tank, signalbeacon); EntityTanker = new EntityGasolineTanker(speed, weight, bodyColor, additionalColor, tank, signalbeacon);
} }
/// <summary>
/// Конструктор через сущность
/// </summary>
/// <param name="car">Объект класса-сущность</param>
public DrawningGasolineTanker(EntityTanker entityTanker) : base()
{
EntityTanker = entityTanker;
}
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {

View File

@ -1,5 +1,5 @@
using ProjectGasolineTanker.Entities; using ProjectGasolineTanker.Entities;
using System; using ProjectGasolineTanker.Drawnings;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -67,7 +67,7 @@ public class DrawningTanker
/// <summary> /// <summary>
/// Пустой конструктор /// Пустой конструктор
/// </summary> /// </summary>
private DrawningTanker() protected DrawningTanker()
{ {
_pictureWidth = null; _pictureWidth = null;
_pictureHeight = null; _pictureHeight = null;
@ -90,17 +90,27 @@ public class DrawningTanker
/// <summary> /// <summary>
/// <param name="drawingBusWidth">Ширина прорисовки танка</param> /// <param name="drawingBusWidth">Ширина прорисовки танка</param>
/// <param name="drawingBusHeight">Высота прорисовки танка</param> /// <param name="drawingBusHeight">Высота прорисовки танка</param>
protected DrawningTanker(int drawningCarWidth, int drawningCarHeight) : this() public DrawningTanker(int drawningCarWidth, int drawningCarHeight) : this()
{ {
_drawningCarWidth = drawningCarWidth; _drawningCarWidth = drawningCarWidth;
_drawningCarHeight = drawningCarHeight; _drawningCarHeight = drawningCarHeight;
} }
/// <summary> /// <summary>
/// Конструктор через сущность
/// </summary>
/// <param name="car">Объект класса-сущность</param>
public DrawningTanker(EntityTanker entityTanker) : base()
{
EntityTanker = entityTanker;
}
/// <summary>
/// Установка границ поля /// Установка границ поля
/// </summary> /// </summary>
/// <param name="width">Ширина поля</param> /// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param> /// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена , нельзя разместить объект в этих размерах</returns> /// <returns>true - границы заданы, false - проверка не пройдена , нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height) public bool SetPictureSize(int width, int height)
{ {

View File

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectGasolineTanker.Entities;
namespace ProjectGasolineTanker.Drawnings;
public static class ExtentionDrawningTanker
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningTanker? CreateDrawningTanker(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTanker? tanker = EntityGasolineTanker.CreateEntityGasolineTanker(strs);
if (tanker != null)
{
return new DrawningGasolineTanker(tanker);
}
tanker = EntityTanker.CreateEntityCar(strs);
if (tanker != null)
{
return new DrawningTanker(tanker);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningTanker">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningTanker drawningTanker)
{
string[]? array = drawningTanker?.EntityTanker?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -9,14 +9,16 @@ public class EntityGasolineTanker : EntityTanker
/// Дополниетльный цвет /// Дополниетльный цвет
/// </summary> /// </summary>
public Color AdditionalColor { get; private set; } public Color AdditionalColor { get; private set; }
public void SetAdditionalColor(Color color) => AdditionalColor = color;
/// <summary> /// <summary>
/// Наличие безнобака /// Наличие безнобака
/// </summary> /// </summary>
public bool Tank { get; private set; } public bool Signalbeacon { get; private set; }
/// <summary> /// <summary>
/// Наличие радара /// Наличие радара
/// </summary> /// </summary>
public bool Signalbeacon { get; private set; } public bool Tank { get; private set; }
/// <summary> /// <summary>
/// Инициализация полей объекта-класса зенитной установки /// Инициализация полей объекта-класса зенитной установки
@ -28,10 +30,33 @@ public class EntityGasolineTanker : EntityTanker
/// <param name="tank">Признак</param> /// <param name="tank">Признак</param>
/// <param name="signalbeacon">Признак </param> /// <param name="signalbeacon">Признак </param>
public EntityGasolineTanker(int speed, double weight, Color bodyColor, Color additionalColor, bool tank, bool signalbeacon) : base(speed, weight, bodyColor) public EntityGasolineTanker(int speed, double weight, Color bodyColor, Color additionalColor, bool signalbeacon, bool tank) : base(speed, weight, bodyColor)
{ {
Signalbeacon = signalbeacon; Signalbeacon = signalbeacon;
Tank = tank; Tank = tank;
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityGasolineTanker), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Signalbeacon.ToString(), Tank.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityGasolineTanker? CreateEntityGasolineTanker(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityGasolineTanker))
{
return null;
}
return new EntityGasolineTanker(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]),
Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
} }

View File

@ -16,6 +16,8 @@ public class EntityTanker
/// Основной цвет /// Основной цвет
/// </summary> /// </summary>
public Color BodyColor { get; private set; } public Color BodyColor { get; private set; }
public void SetBodyColor(Color color) => BodyColor = color;
/// <summary> /// <summary>
/// Перемещение бензовоза /// Перемещение бензовоза
/// </summary> /// </summary>
@ -33,4 +35,27 @@ public class EntityTanker
Weight = weight; Weight = weight;
BodyColor = bodyColor; BodyColor = bodyColor;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityTanker), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTanker? CreateEntityCar(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityTanker))
{
return null;
}
return new EntityTanker(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
} }

View File

@ -0,0 +1,17 @@
using System.Runtime.Serialization;
namespace ProjectGasolineTanker.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) { }
}

View File

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectGasolineTanker.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) { }
}

View File

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectGasolineTanker.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) { }
}

View File

@ -33,7 +33,6 @@ namespace ProjectGasolineTanker
Инструменты = new GroupBox(); Инструменты = new GroupBox();
panelCompanyTools = new Panel(); panelCompanyTools = new Panel();
buttonAddTanker = new Button(); buttonAddTanker = new Button();
buttonAddGasolineTanker = new Button();
maskedTextBoxPosition = new MaskedTextBox(); maskedTextBoxPosition = new MaskedTextBox();
buttonGoToCheck = new Button(); buttonGoToCheck = new Button();
buttonRemoveTanker = new Button(); buttonRemoveTanker = new Button();
@ -49,10 +48,17 @@ namespace ProjectGasolineTanker
labelCollectionName = new Label(); labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
Инструменты.SuspendLayout(); Инструменты.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// Инструменты // Инструменты
@ -62,9 +68,9 @@ namespace ProjectGasolineTanker
Инструменты.Controls.Add(panelStorage); Инструменты.Controls.Add(panelStorage);
Инструменты.Controls.Add(comboBoxSelectorCompany); Инструменты.Controls.Add(comboBoxSelectorCompany);
Инструменты.Dock = DockStyle.Right; Инструменты.Dock = DockStyle.Right;
Инструменты.Location = new Point(861, 0); Инструменты.Location = new Point(861, 24);
Инструменты.Name = "Инструменты"; Инструменты.Name = "Инструменты";
Инструменты.Size = new Size(225, 651); Инструменты.Size = new Size(225, 627);
Инструменты.TabIndex = 0; Инструменты.TabIndex = 0;
Инструменты.TabStop = false; Инструменты.TabStop = false;
Инструменты.Text = "Инструменты"; Инструменты.Text = "Инструменты";
@ -72,38 +78,26 @@ namespace ProjectGasolineTanker
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonAddTanker); panelCompanyTools.Controls.Add(buttonAddTanker);
panelCompanyTools.Controls.Add(buttonAddGasolineTanker);
panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonRemoveTanker); panelCompanyTools.Controls.Add(buttonRemoveTanker);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Location = new Point(3, 383); panelCompanyTools.Location = new Point(3, 380);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(219, 265); panelCompanyTools.Size = new Size(219, 244);
panelCompanyTools.TabIndex = 8; panelCompanyTools.TabIndex = 8;
// //
// buttonAddTanker // buttonAddTanker
// //
buttonAddTanker.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddTanker.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTanker.Location = new Point(3, 3); buttonAddTanker.Location = new Point(3, 21);
buttonAddTanker.Name = "buttonAddTanker"; buttonAddTanker.Name = "buttonAddTanker";
buttonAddTanker.Size = new Size(213, 37); buttonAddTanker.Size = new Size(213, 37);
buttonAddTanker.TabIndex = 1; buttonAddTanker.TabIndex = 1;
buttonAddTanker.Text = "Добавление грузовика"; buttonAddTanker.Text = "Добавление грузовика";
buttonAddTanker.UseVisualStyleBackColor = true; buttonAddTanker.UseVisualStyleBackColor = true;
buttonAddTanker.Click += buttonAddTanker_Click; buttonAddTanker.Click += ButtonAddTanker_Click;
//
// buttonAddGasolineTanker
//
buttonAddGasolineTanker.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddGasolineTanker.Location = new Point(3, 43);
buttonAddGasolineTanker.Name = "buttonAddGasolineTanker";
buttonAddGasolineTanker.Size = new Size(213, 37);
buttonAddGasolineTanker.TabIndex = 2;
buttonAddGasolineTanker.Text = "Добавление бензовоза\r\n";
buttonAddGasolineTanker.UseVisualStyleBackColor = true;
buttonAddGasolineTanker.Click += buttonAddGasolineTanker_Click;
// //
// maskedTextBoxPosition // maskedTextBoxPosition
// //
@ -132,7 +126,7 @@ namespace ProjectGasolineTanker
buttonRemoveTanker.Name = "buttonRemoveTanker"; buttonRemoveTanker.Name = "buttonRemoveTanker";
buttonRemoveTanker.Size = new Size(213, 40); buttonRemoveTanker.Size = new Size(213, 40);
buttonRemoveTanker.TabIndex = 4; buttonRemoveTanker.TabIndex = 4;
buttonRemoveTanker.Text = "Удаление машины"; buttonRemoveTanker.Text = "Удаление автомобиль";
buttonRemoveTanker.UseVisualStyleBackColor = true; buttonRemoveTanker.UseVisualStyleBackColor = true;
buttonRemoveTanker.Click += ButtonRemoveTanker_Click; buttonRemoveTanker.Click += ButtonRemoveTanker_Click;
// //
@ -254,50 +248,101 @@ namespace ProjectGasolineTanker
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(861, 651); pictureBox.Size = new Size(861, 627);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1086, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файл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.Filter = "txt file | *.txt";
//
// FormTankerCollection // FormTankerCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
AutoScroll = true;
ClientSize = new Size(1086, 651); ClientSize = new Size(1086, 651);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(Инструменты); Controls.Add(Инструменты);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormTankerCollection"; Name = "FormTankerCollection";
Text = "Коллекция лодок"; Text = "Коллекция Грузовиков";
Инструменты.ResumeLayout(false); Инструменты.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false); panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout(); panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
private GroupBox Инструменты; private GroupBox Инструменты;
private Button buttonAddTanker;
private ComboBox comboBoxSelectorCompany; private ComboBox comboBoxSelectorCompany;
private Button buttonAddGasolineTanker; private Button buttonAddTanker;
private Button buttonRemoveTanker;
private MaskedTextBox maskedTextBoxPosition; private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox; private PictureBox pictureBox;
private Button buttonRefresh;
private Button buttonRemoveTanker;
private Button buttonGoToCheck; private Button buttonGoToCheck;
private Button buttonRefresh;
private Panel panelStorage; private Panel panelStorage;
private Label labelCollectionName; private Label labelCollectionName;
private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName; private TextBox textBoxCollectionName;
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private RadioButton radioButtonList; private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private Button buttonCollectionAdd;
private ListBox listBoxCollection;
private Button buttonCollectionDel;
private Button buttonCreateCompany; private Button buttonCreateCompany;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
} }
} }

View File

@ -1,5 +1,7 @@
using ProjectGasolineTanker.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProjectGasolineTanker.CollectionGenericObjects;
using ProjectGasolineTanker.Drawnings; using ProjectGasolineTanker.Drawnings;
using ProjectGasolineTanker.Exceptions;
using System.Windows.Forms; using System.Windows.Forms;
namespace ProjectGasolineTanker; namespace ProjectGasolineTanker;
@ -19,13 +21,16 @@ public partial class FormTankerCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormTankerCollection() public FormTankerCollection(ILogger<FormTankerCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
/// <summary> /// <summary>
@ -35,47 +40,7 @@ public partial class FormTankerCollection : Form
/// <param name="e"></param> /// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{ {
switch (comboBoxSelectorCompany.Text) panelCompanyTools.Enabled = false;
{
case "Хранилище":
_company = new CarPark(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawningTanker>());
break;
}
}
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
DrawningTanker _drawningTanker;
Random random = new();
switch (type)
{
case nameof(DrawningTanker):
_drawningTanker = new DrawningTanker(random.Next(30, 70), random.Next(100, 500),
GetColor(random));
break;
case nameof(DrawningGasolineTanker):
_drawningTanker = new DrawningGasolineTanker(random.Next(30, 70), random.Next(100, 500),
GetColor(random), GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + _drawningTanker != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
} }
/// <summary> /// <summary>
@ -83,37 +48,52 @@ public partial class FormTankerCollection : Form
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void buttonAddTanker_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTanker)); private void ButtonAddTanker_Click(object sender, EventArgs e)
{
FormTankerConfig form = new();
form.Show();
form.AddEvent(SetTanker);
}
/// <summary> /// <summary>
/// Добавление спортивного автомобиля /// Добавление автомобиля в коллекцию
/// </summary>
/// <param name="tank"></param>
private void SetTanker(DrawningTanker? tank)
{
try
{
if (_company == null || tank == null)
{
return;
}
if (_company + tank != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + tank.GetDataForSave());
}
}
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("В коллекции превышено допустимое количество элементов");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Удаление объекта
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void buttonAddGasolineTanker_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningGasolineTanker));
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
private void ButtonRemoveTanker_Click(object sender, EventArgs e) private void ButtonRemoveTanker_Click(object sender, EventArgs e)
{
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{ {
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{ {
return; throw new Exception("Входные данные отсутствуют");
} }
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
@ -121,15 +101,18 @@ public partial class FormTankerCollection : Form
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null) if (_company - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Объект удален");
} }
else }
catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не найден объект по позиции " + pos);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -145,11 +128,13 @@ public partial class FormTankerCollection : Form
return; return;
} }
DrawningTanker? car = null; DrawningTanker? tanker = null;
int counter = 100; int counter = 100;
while (car == null) try
{ {
car = _company.GetRandomObject(); while (tanker == null)
{
tanker = _company.GetRandomObject();
counter--; counter--;
if (counter <= 0) if (counter <= 0)
{ {
@ -157,17 +142,21 @@ public partial class FormTankerCollection : Form
} }
} }
if (car == null) if (tanker == null)
{ {
return; return;
} }
FormGasolineTanker form = new() FormGasolineTanker form = new FormGasolineTanker();
{ form.SetTanker = tanker;
SetTanker = car
};
form.ShowDialog(); form.ShowDialog();
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary> /// <summary>
/// Перерисовка коллекции /// Перерисовка коллекции
@ -190,6 +179,9 @@ public partial class FormTankerCollection : Form
MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
try
{
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
{ {
@ -202,6 +194,13 @@ public partial class FormTankerCollection : Form
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems(); RefreshListBoxItems();
_logger.LogInformation("Добавлена коллекция:", textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
/// <summary> /// <summary>
/// Обновление списка в listBoxCollection /// Обновление списка в listBoxCollection
@ -227,13 +226,24 @@ public partial class FormTankerCollection : Form
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems(); RefreshListBoxItems();
_logger.LogInformation("Удалена коллекция: ", listBoxCollection.SelectedItem.ToString());
} }
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void ButtonCreateCompany_Click(object sender, EventArgs e) private void ButtonCreateCompany_Click(object sender, EventArgs e)
{ {
@ -260,4 +270,54 @@ public partial class FormTankerCollection : Form
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RefreshListBoxItems(); RefreshListBoxItems();
} }
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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);
}
}
}
/// <summary>
/// Обработка кнопки загрузки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
} }

View File

@ -117,4 +117,13 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </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>255, 17</value>
</metadata>
</root> </root>

View File

@ -0,0 +1,357 @@
namespace ProjectGasolineTanker
{
partial class FormTankerConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxConfig = new GroupBox();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelYellow = new Panel();
panelBlack = new Panel();
panelGray = new Panel();
panelBlue = new Panel();
panelWhite = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxSignalbeacon = new CheckBox();
checkBoxTanker = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
panelObject = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
groupBoxConfig.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxSignalbeacon);
groupBoxConfig.Controls.Add(checkBoxTanker);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Controls.Add(labelModifiedObject);
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(574, 219);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(315, 12);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(227, 112);
groupBoxColors.TabIndex = 10;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(176, 66);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(34, 34);
panelPurple.TabIndex = 3;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(176, 22);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(34, 34);
panelYellow.TabIndex = 1;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(120, 66);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(34, 34);
panelBlack.TabIndex = 4;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(67, 66);
panelGray.Name = "panelGray";
panelGray.Size = new Size(34, 34);
panelGray.TabIndex = 5;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(120, 22);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(34, 34);
panelBlue.TabIndex = 1;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(15, 66);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(34, 34);
panelWhite.TabIndex = 2;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(67, 22);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(34, 34);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(15, 22);
panelRed.Name = "panelRed";
panelRed.Size = new Size(34, 34);
panelRed.TabIndex = 0;
//
// checkBoxSignalbeacon
//
checkBoxSignalbeacon.AutoSize = true;
checkBoxSignalbeacon.Location = new Point(12, 168);
checkBoxSignalbeacon.Name = "checkBoxSignalbeacon";
checkBoxSignalbeacon.Size = new Size(232, 34);
checkBoxSignalbeacon.TabIndex = 9;
checkBoxSignalbeacon.Text = "Признак наличия сигнального маяка\r\n\r\n";
checkBoxSignalbeacon.UseVisualStyleBackColor = true;
//
// checkBoxTanker
//
checkBoxTanker.AutoSize = true;
checkBoxTanker.Location = new Point(12, 125);
checkBoxTanker.Name = "checkBoxTanker";
checkBoxTanker.Size = new Size(154, 19);
checkBoxTanker.TabIndex = 8;
checkBoxTanker.Text = "Признак наличия бака \r\n";
checkBoxTanker.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(80, 65);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(96, 23);
numericUpDownWeight.TabIndex = 7;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(80, 36);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(96, 23);
numericUpDownSpeed.TabIndex = 6;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 73);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 5;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 38);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 3;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(442, 160);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(100, 33);
labelModifiedObject.TabIndex = 2;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(315, 160);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(100, 33);
labelSimpleObject.TabIndex = 1;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(594, 0);
panelObject.Name = "panelObject";
panelObject.Size = new Size(194, 164);
panelObject.TabIndex = 5;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(108, 9);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(75, 33);
labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += labelAdditionalColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(13, 9);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(75, 33);
labelBodyColor.TabIndex = 2;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += labelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelBodyColor_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(13, 52);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(170, 99);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(607, 184);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(75, 23);
buttonAdd.TabIndex = 6;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(702, 184);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 7;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormTankerConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 219);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(panelObject);
Controls.Add(groupBoxConfig);
Name = "FormTankerConfig";
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private Label labelModifiedObject;
private Label labelSimpleObject;
private CheckBox checkBoxTanker;
private CheckBox checkBoxSignalbeacon;
private GroupBox groupBoxColors;
private Panel panelPurple;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelGray;
private Panel panelBlue;
private Panel panelWhite;
private Panel panelGreen;
private Panel panelRed;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelBodyColor;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,160 @@
using ProjectGasolineTanker.Drawnings;
using ProjectGasolineTanker.Entities;
namespace ProjectGasolineTanker;
public partial class FormTankerConfig : Form
{
private DrawningTanker? _tanker = null;
private event Action<DrawningTanker>? _TankerDelegate;
public FormTankerConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelGray.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="tankerDelegate"></param>
public void AddEvent(Action<DrawningTanker> TankerDelegate)
{
_TankerDelegate += TankerDelegate;
}
/// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_tanker?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_tanker?.SetPosition(15, 15);
_tanker?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(DataFormats.Text) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "labelSimpleObject":
_tanker = new DrawningTanker((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_tanker = new DrawningGasolineTanker((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxTanker.Checked, checkBoxSignalbeacon.Checked);
break;
}
labelBodyColor.BackColor = Color.Empty;
labelAdditionalColor.BackColor = Color.Empty;
DrawObject();
}
/// <summary>
/// Передаем информацию при нажатии на Panel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
(sender as Control)?.DoDragDrop((sender as Control)?.BackColor ?? Color.Black, DragDropEffects.Move | DragDropEffects.Copy);
}
private void labelBodyColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (_tanker != null)
{
_tanker.EntityTanker.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}
}
private void labelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (_tanker is DrawningGasolineTanker)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_tanker?.EntityTanker is EntityGasolineTanker _gasolinetanker)
{
_gasolinetanker.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_tanker != null)
{
_TankerDelegate?.Invoke(_tanker);
Close();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectGasolineTanker namespace ProjectGasolineTanker
{ {
internal static class Program internal static class Program
@ -11,7 +16,32 @@ namespace ProjectGasolineTanker
// 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 FormTankerCollection()); ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormTankerCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
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<FormTankerCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(new ConfigurationBuilder().
AddJsonFile($"{pathNeed}serilog.json").Build()).CreateLogger());
});
} }
} }
} }

View File

@ -8,4 +8,21 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<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>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Applicatoin": "Sample"
}
}
}