Compare commits

..

3 Commits

Author SHA1 Message Date
52ac4d0b2f с 2024-05-22 21:47:10 +04:00
e67b4ffcc2 с 2024-05-22 21:45:38 +04:00
d77894bf52 в 2024-05-22 21:44:22 +04:00
23 changed files with 571 additions and 274 deletions

View File

@ -8,4 +8,15 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </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.Logging.Abstractions" Version="8.0.1" />
<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>
</Project> </Project>

View File

@ -1,4 +1,5 @@
using ProjectArtilleryUnit.Drawnings; using ProjectArtilleryUnit.Drawnings;
using ProjectArtilleryUnit.Exceptions;
namespace ProjectArtilleryUnit.CollectionGenericObjects namespace ProjectArtilleryUnit.CollectionGenericObjects
{ {
@ -28,14 +29,14 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
protected readonly int _pictureHeight; protected readonly int _pictureHeight;
/// <summary> /// <summary>
/// Коллекция крейсеров /// Коллекция артиллерийских установок
/// </summary> /// </summary>
protected ICollectionGenericObjects<DrawningArtilleryUnit>? _collection = null; protected ICollectionGenericObjects<DrawningArtilleryUnit>? _collection = null;
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -96,8 +97,15 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{ {
DrawningArtilleryUnit? obj = _collection?.Get(i); try
obj?.DrawTransport(graphics); {
DrawningArtilleryUnit? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{ }
catch (PositionOutOfCollectionException e)
{ }
} }
return bitmap; return bitmap;
} }

View File

@ -1,4 +1,5 @@
using ProjectArtilleryUnit.Drawnings; using ProjectArtilleryUnit.Drawnings;
using ProjectArtilleryUnit.Exceptions;
namespace ProjectArtilleryUnit.CollectionGenericObjects namespace ProjectArtilleryUnit.CollectionGenericObjects
{ {
@ -41,11 +42,14 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
for (int i = 0; i < (_collection?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{ {
if (_collection.Get(i) != null)
try
{ {
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10); _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
} }
catch (ObjectNotFoundException) { }
catch(PositionOutOfCollectionException e) { }
if (curWidth < width - 1) if (curWidth < width - 1)
curWidth++; curWidth++;

View File

@ -1,4 +1,6 @@
namespace ProjectArtilleryUnit.CollectionGenericObjects using ProjectArtilleryUnit.Exceptions;
namespace ProjectArtilleryUnit.CollectionGenericObjects
{ {
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@ -40,15 +42,17 @@
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
if (position >= Count || position < 0) return null; // TODO выброc позиций, если выход за границы массива
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
// TODO проверка, что не превышено максимальное количество элементов // TODO проверка, что не превышено максимальное количество элементов
// TODO выбром позиций, если переполнение
// TODO вставка в конец набора // TODO вставка в конец набора
if (Count == _maxCount) return -1; if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
@ -58,8 +62,8 @@
// TODO проверка, что не превышено максимальное количество элементов // TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции // TODO проверка позиции
// TODO вставка по позиции // TODO вставка по позиции
if (Count == _maxCount) return -1; if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) return -1; if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
@ -69,7 +73,8 @@
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO удаление объекта из списка // TODO удаление объекта из списка
if (position >= Count || position < 0) return null; // TODO выбром позиций, если выход за границы массива
if (position >= _collection.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;

View File

@ -1,4 +1,4 @@
using ProjectArtilleryUnit.Drawnings; using ProjectArtilleryUnit.Exceptions;
namespace ProjectArtilleryUnit.CollectionGenericObjects namespace ProjectArtilleryUnit.CollectionGenericObjects
{ {
@ -48,26 +48,30 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
if (position >= _collection.Length || position < 0) // TODO выбром позиций, если выход за границы массива
{ return null; } // TODO выбром позиций, если объект пустой
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
// TODO вставка в свободное место набора // TODO вставка в свободное место набора
// TODO выброc позиций, если переполнение
int index = 0; int index = 0;
while (index < _collection.Length) while (index < Count && _collection[index] != null)
{ {
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
index++; index++;
} }
return -1;
if (index < Count)
{
_collection[index] = obj;
return index;
}
throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
@ -77,45 +81,59 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
// ищется свободное место после этой позиции и идет вставка туда // ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до // если нет после, ищем до
// TODO вставка // TODO вставка
if (position >= _collection.Length || position < 0) // TODO выбром позиций, если переполнение
{ return -1; } // TODO выбром позиций, если выход за границы массива
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) if (_collection[position] != null)
{ {
_collection[position] = obj; bool pushed = false;
return position; for (int index = position + 1; index < Count; index++)
}
int index;
for (index = position + 1; index < _collection.Length; ++index)
{
if (_collection[index] == null)
{ {
_collection[position] = obj; if (_collection[index] == null)
return position; {
position = index;
pushed = true;
break;
}
}
if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
} }
} }
for (index = position - 1; index >= 0; --index) _collection[position] = obj;
{ return position;
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
return -1;
} }
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null // TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0) // TODO выбром позиций, если выход за границы массива
{ return null; } // TODO выбром позиций, если объект пустой
T obj = _collection[position]; if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null; _collection[position] = null;
return obj; return temp;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()

View File

@ -1,4 +1,5 @@
using ProjectArtilleryUnit.Drawnings; using ProjectArtilleryUnit.Drawnings;
using ProjectArtilleryUnit.Exceptions;
using System.Text; using System.Text;
namespace ProjectArtilleryUnit.CollectionGenericObjects namespace ProjectArtilleryUnit.CollectionGenericObjects
@ -89,82 +90,80 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
} }
/// <summary> /// <summary>
/// Сохранение информации по автомобилям в хранилище в файл /// Сохранение информации по самолетам в хранилище в файл
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
using (StreamWriter writer = new StreamWriter(filename))
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{ {
writer.Write(_collectionKey); streamWriter.Write(Environment.NewLine);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
if (value.Value.Count == 0)
{ {
StringBuilder sb = new(); continue;
sb.Append(Environment.NewLine); }
// не сохраняем пустые коллекции
if (value.Value.Count == 0) streamWriter.Write(value.Key);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.GetCollectionType);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{ {
continue; continue;
} }
sb.Append(value.Key);
sb.Append(_separatorForKeyValue); streamWriter.Write(data);
sb.Append(value.Value.GetCollectionType); streamWriter.Write(_separatorItems);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
} }
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по автомобилям в хранилище из файла /// Загрузка информации по кораблям в хранилище из файла
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename"></param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> public void LoadData(string filename)
public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не существует");
} }
using (StreamReader fs = File.OpenText(filename))
using (StreamReader sr = new StreamReader(filename))
{ {
string str = fs.ReadLine(); string? str;
if (str == null || str.Length == 0) str = sr.ReadLine();
{ if (str != _collectionKey.ToString())
return false; throw new FormatException("В файле неверные данные");
}
if (!str.StartsWith(_collectionKey))
{
return false;
}
_storages.Clear(); _storages.Clear();
string strs = ""; while ((str = sr.ReadLine()) != null)
while ((strs = fs.ReadLine()) != null)
{ {
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4) if (record.Length != 4)
{ {
continue; continue;
@ -173,24 +172,31 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningArtilleryUnit() is T artilleryUnit) if (elem?.CreateDrawningArtilleryUnit() is T aircraft)
{ {
if (collection.Insert(artilleryUnit) == -1) try
{ {
return false; if (collection.Insert(aircraft) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
return true;
} }
} }

View File

@ -19,20 +19,20 @@ public class DrawningArtilleryUnit
/// </summary> /// </summary>
private int? _pictureHeight; private int? _pictureHeight;
/// <summary> /// <summary>
/// Левая координата прорисовки крейсера /// Левая координата прорисовки артиллерийской установки
/// </summary> /// </summary>
protected int? _startPosX; protected int? _startPosX;
/// <summary> /// <summary>
/// Верхняя кооридната прорисовки крейсера /// Верхняя кооридната прорисовки артиллерийской установки
/// </summary> /// </summary>
protected int? _startPosY; protected int? _startPosY;
/// <summary> /// <summary>
/// Ширина прорисовки крейсера /// Ширина прорисовки артиллерийской установки
/// </summary> /// </summary>
private readonly int _drawningArtilleryUnitWidth = 150; private readonly int _drawningArtilleryUnitWidth = 150;
/// <summary> /// <summary>
/// Высота прорисовки крейсера /// Высота прорисовки артиллерийской установки
/// </summary> /// </summary>
private readonly int _drawningArtilleryUnitHeight = 50; private readonly int _drawningArtilleryUnitHeight = 50;
private readonly int _drawningEnginesWidth = 3; private readonly int _drawningEnginesWidth = 3;

View File

@ -12,9 +12,9 @@ namespace ProjectArtilleryUnit.Drawnings
/// <param name="weight">Вес</param> /// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param> /// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param> /// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="muzzle">Признак наличия вертолетной площадки</param> /// <param name="muzzle">Признак наличия дула</param>
/// <param name="gun">Признак наличия шлюпок</param> /// <param name="gun">Признак наличия ракетной установки</param>
/// <param name="luke">Признак наличия пушки</param> /// <param name="luke">Признак наличия люка</param>
public DrawningMilitaryArtilleryUnit(int speed, double weight, Color bodyColor, Color additionalColor, bool muzzle, bool gun, bool luke) public DrawningMilitaryArtilleryUnit(int speed, double weight, Color bodyColor, Color additionalColor, bool muzzle, bool gun, bool luke)
: base(150, 50) : base(150, 50)

View File

@ -1,7 +1,7 @@
namespace ProjectArtilleryUnit.Entities; namespace ProjectArtilleryUnit.Entities;
/// <summary> /// <summary>
/// Класс-сущность "крейсер" /// Класс-сущность "артиллерийская установка"
/// </summary> /// </summary>
public class EntityArtilleryUnit public class EntityArtilleryUnit
{ {
@ -31,7 +31,7 @@ public class EntityArtilleryUnit
public double Step => Speed * 100 / Weight; public double Step => Speed * 100 / Weight;
/// <summary> /// <summary>
/// Инициализация полей объекта-класса крейсера /// Инициализация полей объекта-класса артиллерийской установки
/// </summary> /// </summary>
/// <param name="speed">скорость</param> /// <param name="speed">скорость</param>
/// <param name="weight">вес</param> /// <param name="weight">вес</param>

View File

@ -3,17 +3,17 @@
internal class EntityMilitaryArtilleryUnit : EntityArtilleryUnit internal class EntityMilitaryArtilleryUnit : EntityArtilleryUnit
{ {
/// <summary> /// <summary>
/// Признак (опция) наличие вертолетной площадки /// Признак (опция) наличие дула
/// </summary> /// </summary>
public bool Muzzle { get; private set; } public bool Muzzle { get; private set; }
/// <summary> /// <summary>
/// Признак (опция) наличие шлюпок /// Признак (опция) наличие ракетной установки
/// </summary> /// </summary>
public bool Gun { get; private set; } public bool Gun { get; private set; }
/// <summary> /// <summary>
/// Признак (опция) наличие пушки /// Признак (опция) наличие люка
/// </summary> /// </summary>
public bool Luke { get; private set; } public bool Luke { get; private set; }

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectArtilleryUnit.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,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectArtilleryUnit.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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectArtilleryUnit.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

@ -75,10 +75,8 @@
groupBoxConfing.Controls.Add(labelSimpleObject); groupBoxConfing.Controls.Add(labelSimpleObject);
groupBoxConfing.Dock = DockStyle.Left; groupBoxConfing.Dock = DockStyle.Left;
groupBoxConfing.Location = new Point(0, 0); groupBoxConfing.Location = new Point(0, 0);
groupBoxConfing.Margin = new Padding(3, 2, 3, 2);
groupBoxConfing.Name = "groupBoxConfing"; groupBoxConfing.Name = "groupBoxConfing";
groupBoxConfing.Padding = new Padding(3, 2, 3, 2); groupBoxConfing.Size = new Size(626, 262);
groupBoxConfing.Size = new Size(548, 196);
groupBoxConfing.TabIndex = 0; groupBoxConfing.TabIndex = 0;
groupBoxConfing.TabStop = false; groupBoxConfing.TabStop = false;
groupBoxConfing.Text = "Параметры"; groupBoxConfing.Text = "Параметры";
@ -93,11 +91,9 @@
groupBoxColors.Controls.Add(panelBlue); groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGreen); groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed); groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(286, 20); groupBoxColors.Location = new Point(327, 26);
groupBoxColors.Margin = new Padding(3, 2, 3, 2);
groupBoxColors.Name = "groupBoxColors"; groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Padding = new Padding(3, 2, 3, 2); groupBoxColors.Size = new Size(280, 154);
groupBoxColors.Size = new Size(245, 116);
groupBoxColors.TabIndex = 9; groupBoxColors.TabIndex = 9;
groupBoxColors.TabStop = false; groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета"; groupBoxColors.Text = "Цвета";
@ -105,82 +101,73 @@
// panelPurple // panelPurple
// //
panelPurple.BackColor = Color.Purple; panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(190, 72); panelPurple.Location = new Point(217, 96);
panelPurple.Margin = new Padding(3, 2, 3, 2);
panelPurple.Name = "panelPurple"; panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(42, 35); panelPurple.Size = new Size(48, 47);
panelPurple.TabIndex = 1; panelPurple.TabIndex = 1;
// //
// panelBlack // panelBlack
// //
panelBlack.BackColor = Color.Black; panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(130, 72); panelBlack.Location = new Point(149, 96);
panelBlack.Margin = new Padding(3, 2, 3, 2);
panelBlack.Name = "panelBlack"; panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(42, 35); panelBlack.Size = new Size(48, 47);
panelBlack.TabIndex = 1; panelBlack.TabIndex = 1;
// //
// panelGray // panelGray
// //
panelGray.BackColor = Color.Gray; panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(72, 72); panelGray.Location = new Point(82, 96);
panelGray.Margin = new Padding(3, 2, 3, 2);
panelGray.Name = "panelGray"; panelGray.Name = "panelGray";
panelGray.Size = new Size(42, 35); panelGray.Size = new Size(48, 47);
panelGray.TabIndex = 1; panelGray.TabIndex = 1;
// //
// panelWhite // panelWhite
// //
panelWhite.BackColor = Color.White; panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(15, 72); panelWhite.Location = new Point(17, 96);
panelWhite.Margin = new Padding(3, 2, 3, 2);
panelWhite.Name = "panelWhite"; panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(42, 35); panelWhite.Size = new Size(48, 47);
panelWhite.TabIndex = 1; panelWhite.TabIndex = 1;
// //
// panelYellow // panelYellow
// //
panelYellow.BackColor = Color.Yellow; panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(190, 23); panelYellow.Location = new Point(217, 31);
panelYellow.Margin = new Padding(3, 2, 3, 2);
panelYellow.Name = "panelYellow"; panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(42, 35); panelYellow.Size = new Size(48, 47);
panelYellow.TabIndex = 1; panelYellow.TabIndex = 1;
// //
// panelBlue // panelBlue
// //
panelBlue.BackColor = Color.Blue; panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(130, 23); panelBlue.Location = new Point(149, 31);
panelBlue.Margin = new Padding(3, 2, 3, 2);
panelBlue.Name = "panelBlue"; panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(42, 35); panelBlue.Size = new Size(48, 47);
panelBlue.TabIndex = 1; panelBlue.TabIndex = 1;
// //
// panelGreen // panelGreen
// //
panelGreen.BackColor = Color.Green; panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(72, 23); panelGreen.Location = new Point(82, 31);
panelGreen.Margin = new Padding(3, 2, 3, 2);
panelGreen.Name = "panelGreen"; panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(42, 35); panelGreen.Size = new Size(48, 47);
panelGreen.TabIndex = 1; panelGreen.TabIndex = 1;
// //
// panelRed // panelRed
// //
panelRed.BackColor = Color.Red; panelRed.BackColor = Color.Red;
panelRed.Location = new Point(15, 23); panelRed.Location = new Point(17, 31);
panelRed.Margin = new Padding(3, 2, 3, 2);
panelRed.Name = "panelRed"; panelRed.Name = "panelRed";
panelRed.Size = new Size(42, 35); panelRed.Size = new Size(48, 47);
panelRed.TabIndex = 0; panelRed.TabIndex = 0;
// //
// checkBoxLuke // checkBoxLuke
// //
checkBoxLuke.AutoSize = true; checkBoxLuke.AutoSize = true;
checkBoxLuke.Location = new Point(5, 163); checkBoxLuke.Location = new Point(6, 217);
checkBoxLuke.Margin = new Padding(3, 2, 3, 2);
checkBoxLuke.Name = "checkBoxLuke"; checkBoxLuke.Name = "checkBoxLuke";
checkBoxLuke.Size = new Size(155, 19); checkBoxLuke.Size = new Size(193, 24);
checkBoxLuke.TabIndex = 8; checkBoxLuke.TabIndex = 8;
checkBoxLuke.Text = "Признак наличие люка"; checkBoxLuke.Text = "Признак наличие люка";
checkBoxLuke.UseVisualStyleBackColor = true; checkBoxLuke.UseVisualStyleBackColor = true;
@ -188,73 +175,68 @@
// checkBoxGun // checkBoxGun
// //
checkBoxGun.AutoSize = true; checkBoxGun.AutoSize = true;
checkBoxGun.Location = new Point(5, 127); checkBoxGun.Location = new Point(6, 169);
checkBoxGun.Margin = new Padding(3, 2, 3, 2);
checkBoxGun.Name = "checkBoxGun"; checkBoxGun.Name = "checkBoxGun";
checkBoxGun.Size = new Size(182, 19); checkBoxGun.Size = new Size(297, 24);
checkBoxGun.TabIndex = 7; checkBoxGun.TabIndex = 7;
checkBoxGun.Text = "Признак наличие установки"; checkBoxGun.Text = "Признак наличие ракетной установки";
checkBoxGun.UseVisualStyleBackColor = true; checkBoxGun.UseVisualStyleBackColor = true;
checkBoxGun.CheckedChanged += checkBoxGun_CheckedChanged; checkBoxGun.CheckedChanged += checkBoxGun_CheckedChanged;
// //
// checkBoxMuzzle // checkBoxMuzzle
// //
checkBoxMuzzle.AutoSize = true; checkBoxMuzzle.AutoSize = true;
checkBoxMuzzle.Location = new Point(5, 92); checkBoxMuzzle.Location = new Point(6, 123);
checkBoxMuzzle.Margin = new Padding(3, 2, 3, 2);
checkBoxMuzzle.Name = "checkBoxMuzzle"; checkBoxMuzzle.Name = "checkBoxMuzzle";
checkBoxMuzzle.Size = new Size(151, 19); checkBoxMuzzle.Size = new Size(189, 24);
checkBoxMuzzle.TabIndex = 6; checkBoxMuzzle.TabIndex = 6;
checkBoxMuzzle.Text = "Признак наличие дула"; checkBoxMuzzle.Text = "Признак наличие дула";
checkBoxMuzzle.UseVisualStyleBackColor = true; checkBoxMuzzle.UseVisualStyleBackColor = true;
checkBoxMuzzle.CheckedChanged += checkBoxMuzzle_CheckedChanged;
// //
// numericUpDownWeight // numericUpDownWeight
// //
numericUpDownWeight.Location = new Point(82, 51); numericUpDownWeight.Location = new Point(94, 68);
numericUpDownWeight.Margin = new Padding(3, 2, 3, 2);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 }); numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 }); numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight"; numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(100, 23); numericUpDownWeight.Size = new Size(114, 27);
numericUpDownWeight.TabIndex = 5; numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 }); numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
// //
// labelWeight // labelWeight
// //
labelWeight.AutoSize = true; labelWeight.AutoSize = true;
labelWeight.Location = new Point(24, 52); labelWeight.Location = new Point(27, 70);
labelWeight.Name = "labelWeight"; labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15); labelWeight.Size = new Size(36, 20);
labelWeight.TabIndex = 4; labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:"; labelWeight.Text = "Вес:";
// //
// numericUpDownSpeed // numericUpDownSpeed
// //
numericUpDownSpeed.Location = new Point(82, 24); numericUpDownSpeed.Location = new Point(94, 32);
numericUpDownSpeed.Margin = new Padding(3, 2, 3, 2);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 }); numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 }); numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed"; numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(100, 23); numericUpDownSpeed.Size = new Size(114, 27);
numericUpDownSpeed.TabIndex = 3; numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 }); numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
// //
// labelSpeed // labelSpeed
// //
labelSpeed.AutoSize = true; labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(10, 24); labelSpeed.Location = new Point(12, 32);
labelSpeed.Name = "labelSpeed"; labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15); labelSpeed.Size = new Size(76, 20);
labelSpeed.TabIndex = 2; labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:"; labelSpeed.Text = "Скорость:";
// //
// labelModifiedObject // labelModifiedObject
// //
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle; labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(416, 152); labelModifiedObject.Location = new Point(476, 203);
labelModifiedObject.Name = "labelModifiedObject"; labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(115, 34); labelModifiedObject.Size = new Size(131, 44);
labelModifiedObject.TabIndex = 1; labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый"; labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter; labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
@ -263,9 +245,9 @@
// labelSimpleObject // labelSimpleObject
// //
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle; labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(286, 152); labelSimpleObject.Location = new Point(327, 203);
labelSimpleObject.Name = "labelSimpleObject"; labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(114, 34); labelSimpleObject.Size = new Size(130, 44);
labelSimpleObject.TabIndex = 0; labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой"; labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter; labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
@ -273,19 +255,17 @@
// //
// pictureBoxObject // pictureBoxObject
// //
pictureBoxObject.Location = new Point(10, 42); pictureBoxObject.Location = new Point(11, 56);
pictureBoxObject.Margin = new Padding(3, 2, 3, 2);
pictureBoxObject.Name = "pictureBoxObject"; pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(160, 94); pictureBoxObject.Size = new Size(183, 125);
pictureBoxObject.TabIndex = 1; pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false; pictureBoxObject.TabStop = false;
// //
// buttonAdd // buttonAdd
// //
buttonAdd.Location = new Point(553, 159); buttonAdd.Location = new Point(632, 212);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd"; buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(82, 22); buttonAdd.Size = new Size(94, 29);
buttonAdd.TabIndex = 2; buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить"; buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true; buttonAdd.UseVisualStyleBackColor = true;
@ -293,10 +273,9 @@
// //
// buttonCancel // buttonCancel
// //
buttonCancel.Location = new Point(648, 159); buttonCancel.Location = new Point(740, 212);
buttonCancel.Margin = new Padding(3, 2, 3, 2);
buttonCancel.Name = "buttonCancel"; buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(82, 22); buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 3; buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена"; buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true; buttonCancel.UseVisualStyleBackColor = true;
@ -307,10 +286,9 @@
panelObject.Controls.Add(labelAdditionalColor); panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor); panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject); panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(553, 9); panelObject.Location = new Point(632, 12);
panelObject.Margin = new Padding(3, 2, 3, 2);
panelObject.Name = "panelObject"; panelObject.Name = "panelObject";
panelObject.Size = new Size(179, 146); panelObject.Size = new Size(205, 194);
panelObject.TabIndex = 4; panelObject.TabIndex = 4;
panelObject.DragDrop += PanelObject_DragDrop; panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter; panelObject.DragEnter += PanelObject_DragEnter;
@ -319,9 +297,9 @@
// //
labelAdditionalColor.AllowDrop = true; labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle; labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(94, 8); labelAdditionalColor.Location = new Point(108, 11);
labelAdditionalColor.Name = "labelAdditionalColor"; labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(73, 28); labelAdditionalColor.Size = new Size(83, 36);
labelAdditionalColor.TabIndex = 3; labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. цвет"; labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter; labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
@ -332,9 +310,9 @@
// //
labelBodyColor.AllowDrop = true; labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle; labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(10, 8); labelBodyColor.Location = new Point(11, 11);
labelBodyColor.Name = "labelBodyColor"; labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(73, 28); labelBodyColor.Size = new Size(83, 36);
labelBodyColor.TabIndex = 2; labelBodyColor.TabIndex = 2;
labelBodyColor.Text = "Цвет"; labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter; labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
@ -343,14 +321,13 @@
// //
// FormArtilleryUnitConfing // FormArtilleryUnitConfing
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(733, 196); ClientSize = new Size(838, 262);
Controls.Add(panelObject); Controls.Add(panelObject);
Controls.Add(buttonCancel); Controls.Add(buttonCancel);
Controls.Add(buttonAdd); Controls.Add(buttonAdd);
Controls.Add(groupBoxConfing); Controls.Add(groupBoxConfing);
Margin = new Padding(3, 2, 3, 2);
Name = "FormArtilleryUnitConfing"; Name = "FormArtilleryUnitConfing";
Text = "Создание объекта"; Text = "Создание объекта";
groupBoxConfing.ResumeLayout(false); groupBoxConfing.ResumeLayout(false);

View File

@ -62,8 +62,8 @@ namespace ProjectArtilleryUnit
/// <summary> /// <summary>
/// Передаем информацию при нажатии на Label /// Передаем информацию при нажатии на Label
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>labelSimpleObject
/// <param name="e"></param> /// <param name="e"></param>labelSimpleObject
private void labelObject_MouseDown(object sender, MouseEventArgs e) private void labelObject_MouseDown(object sender, MouseEventArgs e)
{ {
(sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy); (sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
@ -171,12 +171,6 @@ namespace ProjectArtilleryUnit
ArtilleryUnitDelegate?.Invoke(_artilleryUnit); ArtilleryUnitDelegate?.Invoke(_artilleryUnit);
Close(); Close();
} }
}
private void checkBoxMuzzle_CheckedChanged(object sender, EventArgs e)
{
} }
private void checkBoxGun_CheckedChanged(object sender, EventArgs e) private void checkBoxGun_CheckedChanged(object sender, EventArgs e)

View File

@ -46,10 +46,17 @@
maskedTextBoxPosision = new MaskedTextBox(); maskedTextBoxPosision = new MaskedTextBox();
buttonGetToTest = new Button(); buttonGetToTest = new Button();
pictureBoxArtilleryUnit = new PictureBox(); pictureBoxArtilleryUnit = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxArtilleryUnit).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxArtilleryUnit).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@ -59,21 +66,18 @@
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Controls.Add(panelCompanyTools); groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(522, 0); groupBoxTools.Location = new Point(631, 28);
groupBoxTools.Margin = new Padding(3, 2, 3, 2);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Padding = new Padding(3, 2, 3, 2); groupBoxTools.Size = new Size(222, 651);
groupBoxTools.Size = new Size(182, 490);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "инструменты"; groupBoxTools.Text = "инструменты";
// //
// buttonCreateCompany // buttonCreateCompany
// //
buttonCreateCompany.Location = new Point(18, 259); buttonCreateCompany.Location = new Point(21, 345);
buttonCreateCompany.Margin = new Padding(3, 2, 3, 2);
buttonCreateCompany.Name = "buttonCreateCompany"; buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(163, 20); buttonCreateCompany.Size = new Size(186, 27);
buttonCreateCompany.TabIndex = 7; buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создать компанию"; buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true; buttonCreateCompany.UseVisualStyleBackColor = true;
@ -89,18 +93,16 @@
panelStorage.Controls.Add(textBoxCollectionName); panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName); panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top; panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 18); panelStorage.Location = new Point(3, 23);
panelStorage.Margin = new Padding(3, 2, 3, 2);
panelStorage.Name = "panelStorage"; panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(176, 212); panelStorage.Size = new Size(216, 283);
panelStorage.TabIndex = 6; panelStorage.TabIndex = 6;
// //
// buttonCollectionDel // buttonCollectionDel
// //
buttonCollectionDel.Location = new Point(15, 185); buttonCollectionDel.Location = new Point(17, 247);
buttonCollectionDel.Margin = new Padding(3, 2, 3, 2);
buttonCollectionDel.Name = "buttonCollectionDel"; buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(163, 20); buttonCollectionDel.Size = new Size(186, 27);
buttonCollectionDel.TabIndex = 6; buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию"; buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true; buttonCollectionDel.UseVisualStyleBackColor = true;
@ -109,19 +111,16 @@
// listBoxCollection // listBoxCollection
// //
listBoxCollection.FormattingEnabled = true; listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15; listBoxCollection.Location = new Point(17, 137);
listBoxCollection.Location = new Point(15, 103);
listBoxCollection.Margin = new Padding(3, 2, 3, 2);
listBoxCollection.Name = "listBoxCollection"; listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(163, 79); listBoxCollection.Size = new Size(186, 104);
listBoxCollection.TabIndex = 5; listBoxCollection.TabIndex = 5;
// //
// buttonCollecctionAdd // buttonCollecctionAdd
// //
buttonCollecctionAdd.Location = new Point(15, 78); buttonCollecctionAdd.Location = new Point(17, 104);
buttonCollecctionAdd.Margin = new Padding(3, 2, 3, 2);
buttonCollecctionAdd.Name = "buttonCollecctionAdd"; buttonCollecctionAdd.Name = "buttonCollecctionAdd";
buttonCollecctionAdd.Size = new Size(163, 20); buttonCollecctionAdd.Size = new Size(186, 27);
buttonCollecctionAdd.TabIndex = 4; buttonCollecctionAdd.TabIndex = 4;
buttonCollecctionAdd.Text = "Добавить коллекцию"; buttonCollecctionAdd.Text = "Добавить коллекцию";
buttonCollecctionAdd.UseVisualStyleBackColor = true; buttonCollecctionAdd.UseVisualStyleBackColor = true;
@ -130,10 +129,9 @@
// radioButtonList // radioButtonList
// //
radioButtonList.AutoSize = true; radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(108, 56); radioButtonList.Location = new Point(123, 75);
radioButtonList.Margin = new Padding(3, 2, 3, 2);
radioButtonList.Name = "radioButtonList"; radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19); radioButtonList.Size = new Size(80, 24);
radioButtonList.TabIndex = 3; radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true; radioButtonList.TabStop = true;
radioButtonList.Text = "Список"; radioButtonList.Text = "Список";
@ -142,10 +140,9 @@
// radioButtonMassive // radioButtonMassive
// //
radioButtonMassive.AutoSize = true; radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(15, 56); radioButtonMassive.Location = new Point(17, 75);
radioButtonMassive.Margin = new Padding(3, 2, 3, 2);
radioButtonMassive.Name = "radioButtonMassive"; radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19); radioButtonMassive.Size = new Size(82, 24);
radioButtonMassive.TabIndex = 2; radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true; radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив"; radioButtonMassive.Text = "Массив";
@ -153,18 +150,17 @@
// //
// textBoxCollectionName // textBoxCollectionName
// //
textBoxCollectionName.Location = new Point(15, 24); textBoxCollectionName.Location = new Point(17, 32);
textBoxCollectionName.Margin = new Padding(3, 2, 3, 2);
textBoxCollectionName.Name = "textBoxCollectionName"; textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(163, 23); textBoxCollectionName.Size = new Size(186, 27);
textBoxCollectionName.TabIndex = 1; textBoxCollectionName.TabIndex = 1;
// //
// labelCollectionName // labelCollectionName
// //
labelCollectionName.AutoSize = true; labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(23, 7); labelCollectionName.Location = new Point(26, 9);
labelCollectionName.Name = "labelCollectionName"; labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(122, 15); labelCollectionName.Size = new Size(155, 20);
labelCollectionName.TabIndex = 0; labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции"; labelCollectionName.Text = "Название коллекции";
// //
@ -173,10 +169,9 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(18, 233); comboBoxSelectorCompany.Location = new Point(21, 311);
comboBoxSelectorCompany.Margin = new Padding(3, 2, 3, 2);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(163, 23); comboBoxSelectorCompany.Size = new Size(186, 28);
comboBoxSelectorCompany.TabIndex = 0; comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged_1; comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged_1;
// //
@ -188,32 +183,29 @@
panelCompanyTools.Controls.Add(maskedTextBoxPosision); panelCompanyTools.Controls.Add(maskedTextBoxPosision);
panelCompanyTools.Controls.Add(buttonGetToTest); panelCompanyTools.Controls.Add(buttonGetToTest);
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 284); panelCompanyTools.Location = new Point(3, 379);
panelCompanyTools.Margin = new Padding(3, 2, 3, 2);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(189, 206); panelCompanyTools.Size = new Size(216, 274);
panelCompanyTools.TabIndex = 8; panelCompanyTools.TabIndex = 8;
// //
// ButtonAddArtilleryUnit // ButtonAddArtilleryUnit
// //
ButtonAddArtilleryUnit.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; ButtonAddArtilleryUnit.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonAddArtilleryUnit.BackgroundImageLayout = ImageLayout.Center; ButtonAddArtilleryUnit.BackgroundImageLayout = ImageLayout.Center;
ButtonAddArtilleryUnit.Location = new Point(16, 2); ButtonAddArtilleryUnit.Location = new Point(18, 3);
ButtonAddArtilleryUnit.Margin = new Padding(3, 2, 3, 2);
ButtonAddArtilleryUnit.Name = "ButtonAddArtilleryUnit"; ButtonAddArtilleryUnit.Name = "ButtonAddArtilleryUnit";
ButtonAddArtilleryUnit.Size = new Size(163, 55); ButtonAddArtilleryUnit.Size = new Size(186, 40);
ButtonAddArtilleryUnit.TabIndex = 1; ButtonAddArtilleryUnit.TabIndex = 1;
ButtonAddArtilleryUnit.Text = "добваление артиллерийской установки"; ButtonAddArtilleryUnit.Text = "добваление установки";
ButtonAddArtilleryUnit.UseVisualStyleBackColor = true; ButtonAddArtilleryUnit.UseVisualStyleBackColor = true;
ButtonAddArtilleryUnit.Click += ButtonAddArtilleryUnit_Click; ButtonAddArtilleryUnit.Click += ButtonAddArtilleryUnit_Click;
// //
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRefresh.Location = new Point(16, 170); buttonRefresh.Location = new Point(18, 227);
buttonRefresh.Margin = new Padding(3, 2, 3, 2);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(163, 31); buttonRefresh.Size = new Size(186, 41);
buttonRefresh.TabIndex = 5; buttonRefresh.TabIndex = 5;
buttonRefresh.Text = "обновить"; buttonRefresh.Text = "обновить";
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
@ -222,32 +214,29 @@
// ButtonRemoveArtilleryUnit // ButtonRemoveArtilleryUnit
// //
ButtonRemoveArtilleryUnit.Anchor = AnchorStyles.Right; ButtonRemoveArtilleryUnit.Anchor = AnchorStyles.Right;
ButtonRemoveArtilleryUnit.Location = new Point(16, 88); ButtonRemoveArtilleryUnit.Location = new Point(18, 138);
ButtonRemoveArtilleryUnit.Margin = new Padding(3, 2, 3, 2);
ButtonRemoveArtilleryUnit.Name = "ButtonRemoveArtilleryUnit"; ButtonRemoveArtilleryUnit.Name = "ButtonRemoveArtilleryUnit";
ButtonRemoveArtilleryUnit.Size = new Size(163, 46); ButtonRemoveArtilleryUnit.Size = new Size(186, 40);
ButtonRemoveArtilleryUnit.TabIndex = 3; ButtonRemoveArtilleryUnit.TabIndex = 3;
ButtonRemoveArtilleryUnit.Text = "удалить артиллерийскую установку"; ButtonRemoveArtilleryUnit.Text = "удалить установку";
ButtonRemoveArtilleryUnit.UseVisualStyleBackColor = true; ButtonRemoveArtilleryUnit.UseVisualStyleBackColor = true;
ButtonRemoveArtilleryUnit.Click += ButtonRemoveArtilleryUnit_Click; ButtonRemoveArtilleryUnit.Click += ButtonRemoveArtilleryUnit_Click;
// //
// maskedTextBoxPosision // maskedTextBoxPosision
// //
maskedTextBoxPosision.Location = new Point(16, 61); maskedTextBoxPosision.Location = new Point(17, 105);
maskedTextBoxPosision.Margin = new Padding(3, 2, 3, 2);
maskedTextBoxPosision.Mask = "00"; maskedTextBoxPosision.Mask = "00";
maskedTextBoxPosision.Name = "maskedTextBoxPosision"; maskedTextBoxPosision.Name = "maskedTextBoxPosision";
maskedTextBoxPosision.Size = new Size(164, 23); maskedTextBoxPosision.Size = new Size(187, 27);
maskedTextBoxPosision.TabIndex = 2; maskedTextBoxPosision.TabIndex = 2;
maskedTextBoxPosision.ValidatingType = typeof(int); maskedTextBoxPosision.ValidatingType = typeof(int);
// //
// buttonGetToTest // buttonGetToTest
// //
buttonGetToTest.Anchor = AnchorStyles.Right; buttonGetToTest.Anchor = AnchorStyles.Right;
buttonGetToTest.Location = new Point(16, 138); buttonGetToTest.Location = new Point(18, 184);
buttonGetToTest.Margin = new Padding(3, 2, 3, 2);
buttonGetToTest.Name = "buttonGetToTest"; buttonGetToTest.Name = "buttonGetToTest";
buttonGetToTest.Size = new Size(163, 30); buttonGetToTest.Size = new Size(186, 40);
buttonGetToTest.TabIndex = 4; buttonGetToTest.TabIndex = 4;
buttonGetToTest.Text = "передать на тесты"; buttonGetToTest.Text = "передать на тесты";
buttonGetToTest.UseVisualStyleBackColor = true; buttonGetToTest.UseVisualStyleBackColor = true;
@ -256,21 +245,63 @@
// pictureBoxArtilleryUnit // pictureBoxArtilleryUnit
// //
pictureBoxArtilleryUnit.Dock = DockStyle.Fill; pictureBoxArtilleryUnit.Dock = DockStyle.Fill;
pictureBoxArtilleryUnit.Location = new Point(0, 0); pictureBoxArtilleryUnit.Location = new Point(0, 28);
pictureBoxArtilleryUnit.Margin = new Padding(3, 2, 3, 2);
pictureBoxArtilleryUnit.Name = "pictureBoxArtilleryUnit"; pictureBoxArtilleryUnit.Name = "pictureBoxArtilleryUnit";
pictureBoxArtilleryUnit.Size = new Size(522, 490); pictureBoxArtilleryUnit.Size = new Size(631, 651);
pictureBoxArtilleryUnit.TabIndex = 1; pictureBoxArtilleryUnit.TabIndex = 1;
pictureBoxArtilleryUnit.TabStop = false; pictureBoxArtilleryUnit.TabStop = false;
pictureBoxArtilleryUnit.Click += pictureBoxArtilleryUnit_Click;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(853, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file|*.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file|*.txt";
// //
// FormArtilleryUnitsCollection // FormArtilleryUnitsCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(704, 490); ClientSize = new Size(853, 679);
Controls.Add(pictureBoxArtilleryUnit); Controls.Add(pictureBoxArtilleryUnit);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Margin = new Padding(3, 2, 3, 2); Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormArtilleryUnitsCollection"; Name = "FormArtilleryUnitsCollection";
Text = "FormArtilleryUnitsCollection"; Text = "FormArtilleryUnitsCollection";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
@ -279,7 +310,10 @@
panelCompanyTools.ResumeLayout(false); panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout(); panelCompanyTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxArtilleryUnit).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxArtilleryUnit).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@ -302,5 +336,11 @@
private Button buttonCreateCompany; private Button buttonCreateCompany;
private Button buttonCollectionDel; private Button buttonCollectionDel;
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,6 +1,6 @@
using ProjectArtilleryUnit.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProjectArtilleryUnit.CollectionGenericObjects;
using ProjectArtilleryUnit.Drawnings; using ProjectArtilleryUnit.Drawnings;
using System.Windows.Forms;
namespace ProjectArtilleryUnit namespace ProjectArtilleryUnit
{ {
@ -16,13 +16,19 @@ namespace ProjectArtilleryUnit
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormArtilleryUnitsCollection() public FormArtilleryUnitsCollection(ILogger<FormArtilleryUnitsCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
/// <summary> /// <summary>
@ -35,6 +41,11 @@ namespace ProjectArtilleryUnit
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
} }
/// <summary>
/// добавление артиллерийской установки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddArtilleryUnit_Click(object sender, EventArgs e) private void ButtonAddArtilleryUnit_Click(object sender, EventArgs e)
{ {
FormArtilleryUnitConfing form = new(); FormArtilleryUnitConfing form = new();
@ -48,21 +59,24 @@ namespace ProjectArtilleryUnit
/// Добавление артиллерийской установки в коллекцию /// Добавление артиллерийской установки в коллекцию
/// </summary> /// </summary>
/// <param name="artilleryUnit"></param> /// <param name="artilleryUnit"></param>
private void SetArtilleryUnit(DrawningArtilleryUnit artilleryUnit) private void SetArtilleryUnit(DrawningArtilleryUnit? artilleryUnit)
{ {
if (_company == null || artilleryUnit == null) if (_company == null || artilleryUnit == null)
{ {
return; return;
} }
try
if (_company + artilleryUnit != -1)
{ {
var res = _company + artilleryUnit;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBoxArtilleryUnit.Image = _company.Show(); pictureBoxArtilleryUnit.Image = _company.Show();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
} }
} }
@ -83,14 +97,18 @@ namespace ProjectArtilleryUnit
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosision.Text); int pos = Convert.ToInt32(maskedTextBoxPosision.Text);
if (_company - pos != null) try
{ {
MessageBox.Show("объект удален"); var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBoxArtilleryUnit.Image = _company.Show(); pictureBoxArtilleryUnit.Image = _company.Show();
} }
else catch (Exception ex)
{ {
MessageBox.Show("не удалось удалить объект"); MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
} }
} }
@ -143,8 +161,7 @@ namespace ProjectArtilleryUnit
{ {
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
@ -156,8 +173,18 @@ namespace ProjectArtilleryUnit
{ {
collectionType = CollectionType.List; collectionType = CollectionType.List;
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems(); try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
} }
/// <summary> /// <summary>
@ -177,6 +204,7 @@ namespace ProjectArtilleryUnit
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
@ -197,7 +225,7 @@ namespace ProjectArtilleryUnit
} }
/// <summary> /// <summary>
/// /// Создание компании
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
@ -208,6 +236,7 @@ namespace ProjectArtilleryUnit
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
ICollectionGenericObjects<DrawningArtilleryUnit>? collection = ICollectionGenericObjects<DrawningArtilleryUnit>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null) if (collection == null)
@ -215,16 +244,68 @@ namespace ProjectArtilleryUnit
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
return; return;
} }
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": case "Хранилище":
_company = new ArtilleryUnitDockingService(pictureBoxArtilleryUnit.Width, pictureBoxArtilleryUnit.Height, collection); _company = new ArtilleryUnitDockingService(pictureBoxArtilleryUnit.Width, pictureBoxArtilleryUnit.Height, collection);
_logger.LogInformation("Компания создана");
break; break;
} }
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
} }
/// <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);
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void pictureBoxArtilleryUnit_Click(object sender, EventArgs e)
{
}
} }
} }

View File

@ -117,4 +117,16 @@
<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, 1</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>145, 1</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>310, 1</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root> </root>

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectArtilleryUnit namespace ProjectArtilleryUnit
{ {
internal static class Program internal static class Program
@ -10,7 +15,31 @@ namespace ProjectArtilleryUnit
{ {
// To customize application configuration such as set high DPI settings or default font, see https://aka.ms/applicationconfiguration. // To customize application configuration such as set high DPI settings or default font, see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormArtilleryUnitsCollection()); ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormArtilleryUnitsCollection>());
} }
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormArtilleryUnitsCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
} }
} }

View File

@ -0,0 +1,14 @@
<?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="artilleryUnitlog-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

View 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": "artilleryUnit"
}
}
}