7 Commits
Lab06 ... Lab08

Author SHA1 Message Date
84e4affbde final 2024-06-05 13:22:48 +04:00
e971b264e6 LAB08 2024-06-05 12:32:48 +04:00
93274b9a00 переделал метод прорисовки заднего фона 2024-05-21 03:46:06 +04:00
ef1bec9f3c переделал метод прорисовки заднего фона 2024-05-21 03:45:30 +04:00
6ead7f2b69 finish 2024-05-21 03:28:00 +04:00
5e46d4770d 1 2024-05-21 03:17:11 +04:00
1dc111bb61 123 2024-05-21 01:53:54 +04:00
20 changed files with 779 additions and 347 deletions

View File

@@ -8,6 +8,15 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -40,7 +40,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
@@ -62,9 +62,9 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param>
/// <param name="boat">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningAirPlane boat)
public static int operator +(AbstractCompany company, DrawningAirPlane airPlane)
{
return company._collection?.Insert(boat) ?? -1;
return company._collection?.Insert(airPlane, new DrawningAirPlaneEqutables()) ?? -1;
}
/// <summary>
@@ -101,8 +101,13 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningAirPlane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningAirPlane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception) { }
}
return bitmap;
@@ -118,4 +123,6 @@ public abstract class AbstractCompany
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}
public void Sort(IComparer<DrawningAirPlane?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@@ -32,10 +32,12 @@ public class AirPlaneSharingService : AbstractCompany
int offsetX = 10, offsetY = -12;
int x = _pictureWidth - _placeSizeWidth, y = offsetY;
numRows = 0;
while (y + _placeSizeHeight <= _pictureHeight)
int adjustedHeight = _pictureHeight - (_placeSizeHeight + 5 + offsetY);
while (y + _placeSizeHeight <= adjustedHeight)
{
int numCols = 0;
int initialX = x; // сохраняем начальное значение x
int initialX = x;
while (x >= 0)
{
numCols++;
@@ -45,12 +47,13 @@ public class AirPlaneSharingService : AbstractCompany
x -= _placeSizeWidth + 2;
}
numRows++;
x = initialX; // возвращаем x к начальному значению после завершения строки
x = initialX;
y += _placeSizeHeight + 5 + offsetY;
}
numCols = numCols; // сохраняем значение numCols для использования в других методах
numCols = numCols;
}
protected override void SetObjectsPosition()
{
if (locCoord == null || _collection == null)
@@ -60,8 +63,12 @@ public class AirPlaneSharingService : AbstractCompany
int row = numRows - 1, col = numCols;
for (int i = 0; i < _collection?.Count; i++, col--)
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9);
try
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9);
}
catch (Exception) { }
if (col == 1)
{
col = numCols + 1;

View File

@@ -0,0 +1,45 @@
using AirBomber.CollectionGenericObjects;
namespace AirBomber.CollectionGenericObjects;
public class CollectionInfo : IEquatable<CollectionInfo>
{
public string Name { get; private set; }
public CollectionType CollectionType { get; private set; }
public string Description { get; private set; }
private static readonly string _separator = "-";
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator,
StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0],
(CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ?
strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@@ -4,6 +4,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.Drawnings;
public interface ICollectionGenericObjects<T>
where T : class
@@ -23,7 +24,7 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
@@ -31,7 +32,7 @@ public interface ICollectionGenericObjects<T>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@@ -57,4 +58,10 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns></returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@@ -1,4 +1,6 @@
using System;
using AirBomber.Drawnings;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -40,30 +42,38 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
return _collection[position];
}
else
{
return null;
}
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount) { return -1; }
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position >= Count || Count == _maxCount)
if (comparer != null)
{
return -1;
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (position < 0 || position >= Count)
throw new PositionOutOfCollectionException(position);
if (Count == _maxCount)
throw new CollectionOverflowException(Count);
_collection.Insert(position, obj);
return position;
@@ -71,7 +81,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
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];
_collection.RemoveAt(position);
return obj;
@@ -84,4 +94,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@@ -1,4 +1,6 @@
using System;
using AirBomber.Drawnings;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -49,16 +51,21 @@ where T : class
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
return _collection[position];
}
return null;
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?> comparer = null)
{
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningAirPlane>).Equals(obj as DrawningAirPlane, item as DrawningAirPlane))
throw new ObjectIsEqualException();
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@@ -67,14 +74,22 @@ where T : class
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningAirPlane>).Equals(obj as DrawningAirPlane, item as DrawningAirPlane))
throw new ObjectIsEqualException();
}
}
if (position < 0 || position >= Count)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
@@ -99,15 +114,16 @@ where T : class
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position];
_collection[position] = null;
return obj;
@@ -120,4 +136,9 @@ where T : class
yield return _collection[i];
}
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@@ -1,4 +1,5 @@
using AirBomber.Drawnings;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -16,12 +17,12 @@ public class StorageCollection<T>
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
@@ -43,7 +44,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@@ -53,17 +54,18 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
return;
}
switch (collectionType)
{
case CollectionType.Massive:
_storages[name] = new MassiveGenericObjects<T>();
_storages[collectionInfo] = new MassiveGenericObjects<T>();
break;
case CollectionType.List:
_storages[name] = new ListGenericObjects<T>();
_storages[collectionInfo] = new ListGenericObjects<T>();
break;
default:
return;
@@ -76,11 +78,11 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (_storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
_storages.Remove(name);
_storages.Remove(collectionInfo);
}
}
/// <summary>
@@ -92,10 +94,9 @@ public class StorageCollection<T>
{
get
{
if (_storages.ContainsKey(name))
{
return _storages[name];
}
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
@@ -105,11 +106,11 @@ public class StorageCollection<T>
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@@ -122,15 +123,13 @@ public class StorageCollection<T>
using (StreamWriter sw = new StreamWriter(filename))
{
sw.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> kvpair in _storages)
foreach (KeyValuePair<CollectionInfo, 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())
@@ -145,7 +144,6 @@ public class StorageCollection<T>
sb.Clear();
}
}
return true;
}
/// <summary>
@@ -153,50 +151,60 @@ public class StorageCollection<T>
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str != _collectionKey.ToString())
return false;
if (str == null || str.Length == 0)
throw new Exception("В файле нет данных");
if (!str.StartsWith(_collectionKey))
throw new Exception("В файле неверные данные");
_storages.Clear();
while ((str = sr.ReadLine()) != null)
string strs = "";
while ((strs = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4)
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
if (collection == null)
{
return false;
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningAirPlane() is T boat)
{
if (collection.Insert(boat) == -1)
return false;
try
{
if (collection.Insert(boat) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
return true;
}
/// <summary>

View File

@@ -0,0 +1,28 @@
namespace AirBomber.Drawnings;
public class DrawningBoatCompareByColor : IComparer<DrawningAirPlane?>
{
public int Compare(DrawningAirPlane? x, DrawningAirPlane? y)
{
if (x == null || x.EntityAirPlane == null)
{
return 1;
}
if (y == null || y.EntityAirPlane == null)
{
return -1;
}
var bodycolorCompare = x.EntityAirPlane.BodyColor.Name.CompareTo(y.EntityAirPlane.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityAirPlane.Speed.CompareTo(y.EntityAirPlane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityAirPlane.Weight.CompareTo(y.EntityAirPlane.Weight);
}
}

View File

@@ -0,0 +1,29 @@
namespace AirBomber.Drawnings;
public class DrawningAirPlaneCompareByType : IComparer<DrawningAirPlane?>
{
public int Compare(DrawningAirPlane? x, DrawningAirPlane? y)
{
if (x == null || x.EntityAirPlane == null)
{
return 1;
}
if (y == null || y.EntityAirPlane == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityAirPlane.Speed.CompareTo(y.EntityAirPlane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityAirPlane.Weight.CompareTo(y.EntityAirPlane.Weight);
}
}

View File

@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
using AirBomber.Entities;
namespace AirBomber.Drawnings;
public class DrawningAirPlaneEqutables : IEqualityComparer<DrawningAirPlane>
{
public bool Equals(DrawningAirPlane? x, DrawningAirPlane? y)
{
if (x == null || x.EntityAirPlane == null)
{
return false;
}
if (y == null || y.EntityAirPlane == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityAirPlane.Speed != y.EntityAirPlane.Speed)
{
return false;
}
if (x.EntityAirPlane.Weight != y.EntityAirPlane.Weight)
{
return false;
}
if (x.EntityAirPlane.BodyColor != y.EntityAirPlane.BodyColor)
{
return false;
}
if (x is DrawningAirBomber && y is DrawningAirBomber)
{
EntityAirBomber _x = (EntityAirBomber)x.EntityAirPlane;
EntityAirBomber _y = (EntityAirBomber)x.EntityAirPlane;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.Bombs != _y.Bombs)
{
return false;
}
if (_x.FuelTanks != _y.FuelTanks)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningAirPlane obj)
{
return obj.GetHashCode();
}
}

View File

@@ -0,0 +1,17 @@
using System.Runtime.Serialization;
namespace AirBomber.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,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public class ObjectIsEqualException : ApplicationException
{
public ObjectIsEqualException(int count) : base("В коллекции содержится равный элемент: " + count) { }
public ObjectIsEqualException() : base() { }
public ObjectIsEqualException(string message) : base(message) { }
public ObjectIsEqualException(string message, Exception exception) : base(message, exception) { }
protected ObjectIsEqualException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

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

@@ -30,6 +30,8 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonAddAirPlane = new Button();
maskedTextBox = new MaskedTextBox();
buttonRefresh = new Button();
@@ -66,34 +68,54 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(859, 0);
groupBoxTools.Margin = new Padding(3, 4, 3, 4);
groupBoxTools.Location = new Point(752, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Padding = new Padding(3, 4, 3, 4);
groupBoxTools.Size = new Size(238, 859);
groupBoxTools.Size = new Size(208, 659);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструманты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddAirPlane);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonDelAirPlane);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Location = new Point(16, 456);
panelCompanyTools.Location = new Point(12, 315);
panelCompanyTools.Margin = new Padding(3, 2, 3, 2);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(210, 285);
panelCompanyTools.Size = new Size(184, 339);
panelCompanyTools.TabIndex = 8;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(6, 295);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(175, 37);
buttonSortByColor.TabIndex = 9;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(6, 255);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(175, 38);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonAddAirPlane
//
buttonAddAirPlane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddAirPlane.Location = new Point(7, 4);
buttonAddAirPlane.Margin = new Padding(3, 4, 3, 4);
buttonAddAirPlane.Location = new Point(6, 3);
buttonAddAirPlane.Name = "buttonAddAirPlane";
buttonAddAirPlane.Size = new Size(200, 55);
buttonAddAirPlane.Size = new Size(175, 41);
buttonAddAirPlane.TabIndex = 1;
buttonAddAirPlane.Text = "Добавление самолета";
buttonAddAirPlane.UseVisualStyleBackColor = true;
@@ -101,20 +123,18 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(7, 131);
maskedTextBox.Margin = new Padding(3, 4, 3, 4);
maskedTextBox.Location = new Point(6, 98);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(201, 27);
maskedTextBox.Size = new Size(176, 23);
maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonRefresh
//
buttonRefresh.Location = new Point(7, 243);
buttonRefresh.Margin = new Padding(3, 4, 3, 4);
buttonRefresh.Location = new Point(6, 212);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(200, 29);
buttonRefresh.Size = new Size(175, 37);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@@ -123,10 +143,9 @@
// buttonDelAirPlane
//
buttonDelAirPlane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelAirPlane.Location = new Point(7, 165);
buttonDelAirPlane.Margin = new Padding(3, 4, 3, 4);
buttonDelAirPlane.Location = new Point(6, 124);
buttonDelAirPlane.Name = "buttonDelAirPlane";
buttonDelAirPlane.Size = new Size(200, 31);
buttonDelAirPlane.Size = new Size(175, 38);
buttonDelAirPlane.TabIndex = 4;
buttonDelAirPlane.Text = "Удалить Самолет";
buttonDelAirPlane.UseVisualStyleBackColor = true;
@@ -134,10 +153,9 @@
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(7, 205);
buttonGoToCheck.Margin = new Padding(3, 4, 3, 4);
buttonGoToCheck.Location = new Point(6, 168);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(200, 29);
buttonGoToCheck.Size = new Size(175, 38);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@@ -145,9 +163,10 @@
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(16, 365);
buttonCreateCompany.Location = new Point(14, 274);
buttonCreateCompany.Margin = new Padding(3, 2, 3, 2);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(207, 49);
buttonCreateCompany.Size = new Size(181, 37);
buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
@@ -163,16 +182,18 @@
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 24);
panelStorage.Location = new Point(3, 19);
panelStorage.Margin = new Padding(3, 2, 3, 2);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(232, 304);
panelStorage.Size = new Size(202, 228);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(13, 271);
buttonCollectionDel.Location = new Point(11, 203);
buttonCollectionDel.Margin = new Padding(3, 2, 3, 2);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(210, 29);
buttonCollectionDel.Size = new Size(184, 22);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллецию";
buttonCollectionDel.UseVisualStyleBackColor = true;
@@ -181,17 +202,19 @@
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 20;
listBoxCollection.Location = new Point(3, 161);
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 121);
listBoxCollection.Margin = new Padding(3, 2, 3, 2);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(220, 104);
listBoxCollection.Size = new Size(193, 79);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(13, 125);
buttonCollectionAdd.Location = new Point(11, 94);
buttonCollectionAdd.Margin = new Padding(3, 2, 3, 2);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(216, 29);
buttonCollectionAdd.Size = new Size(189, 22);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллецию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
@@ -200,9 +223,10 @@
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(101, 96);
radioButtonList.Location = new Point(84, 72);
radioButtonList.Margin = new Padding(3, 2, 3, 2);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(80, 24);
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
@@ -211,9 +235,10 @@
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(13, 96);
radioButtonMassive.Location = new Point(11, 72);
radioButtonMassive.Margin = new Padding(3, 2, 3, 2);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(82, 24);
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
@@ -221,17 +246,18 @@
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(3, 53);
textBoxCollectionName.Location = new Point(3, 40);
textBoxCollectionName.Margin = new Padding(3, 2, 3, 2);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(226, 27);
textBoxCollectionName.Size = new Size(198, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(13, 12);
labelCollectionName.Location = new Point(11, 9);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(151, 20);
labelCollectionName.Size = new Size(119, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллеции:";
//
@@ -241,10 +267,9 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(16, 331);
comboBoxSelectorCompany.Margin = new Padding(3, 4, 3, 4);
comboBoxSelectorCompany.Location = new Point(14, 248);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(210, 28);
comboBoxSelectorCompany.Size = new Size(184, 23);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged;
//
@@ -252,9 +277,8 @@
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Margin = new Padding(3, 4, 3, 4);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(859, 859);
pictureBox.Size = new Size(752, 659);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@@ -264,8 +288,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(7, 3, 0, 3);
menuStrip.Size = new Size(859, 30);
menuStrip.Size = new Size(752, 24);
menuStrip.TabIndex = 3;
menuStrip.Text = "menuStrip1";
//
@@ -273,15 +296,14 @@
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
файлToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
@@ -289,7 +311,7 @@
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
@@ -303,13 +325,12 @@
//
// FormAirPlaneCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1097, 859);
ClientSize = new Size(960, 659);
Controls.Add(menuStrip);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Margin = new Padding(3, 4, 3, 4);
Name = "FormAirPlaneCollection";
Text = "FormAirPlaneCollection";
Load += FormAirPlaneCollection_Load;
@@ -351,5 +372,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@@ -9,64 +9,72 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using AirBomber.Exceptions;
namespace AirBomber
namespace AirBomber;
public partial class FormAirPlaneCollection : Form
{
public partial class FormAirPlaneCollection : Form
/// <summary>
/// Хранилище коллекций
/// </summary>
private readonly StorageCollection<DrawningAirPlane> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormAirPlaneCollection(ILogger<FormAirPlaneCollection> logger)
{
/// <summary>
/// Хранилище коллекций
/// </summary>
private readonly StorageCollection<DrawningAirPlane> _storageCollection;
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company;
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Конструктор
/// </summary>
public FormAirPlaneCollection()
{
InitializeComponent();
_storageCollection = new();
}
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
/// <summary>
/// Добавление самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddAirPlane_Click(object sender, EventArgs e)
{
FormAirPlaneConfig form = new();
//TODO передать метод
form.Show();
form.AddEvent(SetAirPlane);
}
/// <summary>
/// Добавление самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddAirPlane_Click(object sender, EventArgs e)
{
FormAirPlaneConfig form = new();
//TODO передать метод
form.Show();
form.AddEvent(SetAirPlane);
}
/// <summary>
/// Добавление самолета в коллекцию
/// </summary>
/// <param name="airplane"></param>
private void SetAirPlane(DrawningAirPlane airplane)
/// <summary>
/// Добавление самолета в коллекцию
/// </summary>
/// <param name="airplane"></param>
private void SetAirPlane(DrawningAirPlane airplane)
{
try
{
if (_company == null || airplane == null)
{
@@ -77,41 +85,35 @@ namespace AirBomber
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + airplane.GetDataForSave());
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
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;
MessageBox.Show("В коллекции превышено допустимое количество элементов");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectIsEqualException ex)
{
MessageBox.Show("Такой объект уже существует в коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveAirPlane_Click(object sender, EventArgs e)
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveAirPlane_Click(object sender, EventArgs e)
{
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
return;
throw new Exception("Входные данные отсутствуют");
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
@@ -119,35 +121,40 @@ namespace AirBomber
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation("Объект удален");
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
catch (Exception ex)
{
if (_company == null)
{
return;
}
MessageBox.Show("Не найден объект по позиции " + pos);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
DrawningAirPlane? airplane = null;
int counter = 100;
while (airplane == null)
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningAirPlane? airPlane = null;
int counter = 100;
try
{
while (airPlane == null)
{
airplane = _company.GetRandomObject();
airPlane = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
@@ -155,43 +162,51 @@ namespace AirBomber
}
}
if (airplane == null)
if (airPlane == null)
{
return;
}
FormAirBomber form = new FormAirBomber();
form.SetAirPlane = airplane;
form.SetAirPlane = airPlane;
form.ShowDialog();
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
catch (Exception ex)
{
if (_company == null)
{
return;
}
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
pictureBox.Image = _company.Show();
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
private void FormAirPlaneCollection_Load(object sender, EventArgs e)
{
pictureBox.Image = _company.Show();
}
private void FormAirPlaneCollection_Load(object sender, EventArgs e)
{
}
private void buttonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
private void buttonCollectionAdd_Click(object sender, EventArgs e)
try
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
@@ -204,105 +219,148 @@ namespace AirBomber
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_logger.LogInformation("Добавлена коллекция:", textBoxCollectionName.Text);
}
private void RefreshListBoxItems()
catch (Exception ex)
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void RefreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
listBoxCollection.Items.Add(colName);
}
}
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
private void buttonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
try
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
_logger.LogInformation("Удалена коллекция: ", listBoxCollection.SelectedItem.ToString());
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateCompany_Click(object sender, EventArgs e)
catch (Exception ex)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningAirPlane>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new AirPlaneSharingService(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
_logger.LogError("Ошибка: {Message}", ex.Message);
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
MessageBox.Show("Коллекция не выбрана");
return;
}
/// <summary>
/// Обработка кнопки загрузки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
ICollectionGenericObjects<DrawningAirPlane>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new AirPlaneSharingService(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
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
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
RefreshListBoxItems();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_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);
}
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareAirPlane(new DrawningAirPlaneCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareAirPlane(new DrawningBoatCompareByColor());
}
private void CompareAirPlane(IComparer<DrawningAirPlane?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@@ -18,7 +18,7 @@
<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="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>

View File

@@ -1,17 +1,45 @@
namespace AirBomber
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace AirBomber;
internal static class Program
{
internal static class Program
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormAirPlaneCollection());
}
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormAirPlaneCollection>());
}
}
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<FormAirPlaneCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(new ConfigurationBuilder().
AddJsonFile($"{pathNeed}serilog.json").Build()).CreateLogger());
});
}
}

15
AirBomber/serilog.json Normal file
View File

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