5 Commits
Lab05 ... Lab07

Author SHA1 Message Date
bd4c44628c Исправил эксепшеоны 2024-06-13 15:59:00 +04:00
f9a01c77fa Доделал лаб07 2024-06-12 16:40:18 +04:00
b614557ff8 Поделал лаб07 2024-05-21 22:03:41 +04:00
bf7ba3ecc4 Cдал лаб06 2024-05-08 13:29:38 +04:00
d246f06d90 Поделал лаб06 2024-05-07 23:59:46 +04:00
20 changed files with 702 additions and 88 deletions

View File

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

View File

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

View File

@@ -1,4 +1,8 @@
namespace ProjectSeaplane.CollectionGenericObjects;

using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
@@ -12,7 +16,22 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount
{
get
{
return Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
@@ -23,14 +42,14 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
// TODO проверка позиции
if (position >= Count || position < 0) return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора
if (Count == _maxCount) return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
@@ -39,8 +58,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
if (Count == _maxCount) return -1;
if (position >= Count || position < 0) return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
}
@@ -48,9 +67,17 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
// TODO проверка позиции
// TODO удаление объекта из списка
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;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; i++)
{
yield return _collection[i];
}
}
}

View File

@@ -1,4 +1,7 @@
namespace ProjectSeaplane.CollectionGenericObjects;

using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@@ -13,8 +16,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@@ -31,6 +39,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@@ -41,11 +51,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
// TODO проверка позиции
if (position >= _collection.Length || position < 0)
{
return null;
}
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
@@ -63,7 +70,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
index++;
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
@@ -74,8 +81,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
// если нет после, ищем до
// TODO вставка
if (position >= _collection.Length || position < 0)
{
return -1;
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
@@ -102,19 +109,25 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return position;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0)
{
return null;
}
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position];
_collection[position] = null;
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; i++)
{
yield return _collection[i];
}
}
}

View File

@@ -1,4 +1,5 @@
using ProjectSeaplane.Drawnings;
using ProjectSeaplane.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -49,11 +50,18 @@ public class PlanePark : AbstractCompany
}
for (int x = _pictureWidth - 200; x - 120 > 0; x -= _placeSizeHeight + 75)
{
_collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(count)?.SetPosition(x, y);
count++;
if (count < _collection?.Count)
{
try
{
_collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(count)?.SetPosition(x, y);
count++;
}
catch (ObjectNotFoundException) { }
}
}
}
}
}

View File

@@ -1,19 +1,40 @@
namespace ProjectSeaplane.CollectionGenericObjects;
using ProjectSeaplane.Drawnings;
using ProjectSeaplane.Exceptions;
using System.Text;
namespace ProjectSeaplane.CollectionGenericObjects;
/// <summary>
/// класс-хранилище
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawingBasicSeaplane
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
@@ -61,7 +82,135 @@ public class StorageCollection<T>
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name))
return _storages[name];
return null;
}
}
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при
///сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
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);
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке
///данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new InvalidDataException("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
throw new InvalidDataException("В файле неверные данные");
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBasicSeaplane() is T seaplane)
{
try
{
if (collection.Insert(seaplane) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
} catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@@ -93,6 +93,10 @@ public class DrawingBasicSeaplane
_drawningSeaplaneHeight = drawningSeaplaneHeight;
}
public DrawingBasicSeaplane(EntityBasicSeaplane seaplane) : this()
{
EntityBasicSeaplane = new EntityBasicSeaplane(seaplane.Speed, seaplane.Weight, seaplane.BodyColor);
}
/// <summary>
/// Установка границ поля

View File

@@ -1,4 +1,5 @@
using ProjectSeaplane.Entities;
using System.Windows.Forms.Design.Behavior;
namespace ProjectSeaplane.Drawnings;
/// <summary>
@@ -31,6 +32,10 @@ public class DrawingSeaplane : DrawingBasicSeaplane
EntityBasicSeaplane = new EntitySeaplane(speed, weight, bodyColor, additionalColor, landingGear, radar);
}
public DrawingSeaplane(EntitySeaplane seaplane) : base(155, 70)
{
EntityBasicSeaplane = new EntitySeaplane(seaplane.Speed, seaplane.Weight, seaplane.BodyColor, seaplane.AdditionalColor, seaplane.LandingGear, seaplane.Radar);
}
public override void DrawTransport(Graphics g)
{
@@ -49,9 +54,9 @@ public class DrawingSeaplane : DrawingBasicSeaplane
g.DrawLine(penKraya, _startPosX.Value + 70, _startPosY.Value + 53, _startPosX.Value + 90, _startPosY.Value + 63);
}
//Чет надо но не понял
base.DrawTransport(g);
//also
if (seaplane.Radar)
{
Point point5 = new Point(_startPosX.Value + 50, _startPosY.Value + 22);

View File

@@ -0,0 +1,47 @@
using ProjectSeaplane.Entities;
namespace ProjectSeaplane.Drawnings;
/// <summary>
/// расширение для класса EntitySeaplane
/// </summary>
public static class ExtentionDrawningBasicSeaplane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawingBasicSeaplane? CreateDrawningBasicSeaplane(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityBasicSeaplane? seaplane = EntitySeaplane.CreateEntitySeaplane(strs);
if (seaplane != null)
{
return new DrawingSeaplane((EntitySeaplane)seaplane);
}
seaplane = EntityBasicSeaplane.CreateEntityBasicSeaplane(strs);
if (seaplane!= null)
{
return new DrawingBasicSeaplane(seaplane);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningBasicSeaplane">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingBasicSeaplane drawningBasicSeaplane)
{
string[]? array = drawningBasicSeaplane?.EntityBasicSeaplane?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -41,5 +41,26 @@ public class EntityBasicSeaplane
Weight = weight;
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityBasicSeaplane), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityBasicSeaplane? CreateEntityBasicSeaplane(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityBasicSeaplane))
{
return null;
}
return new EntityBasicSeaplane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@@ -1,4 +1,6 @@

using System.Net.Sockets;
namespace ProjectSeaplane.Entities;
/// <summary>
/// Класс-сущность "Гидросамолет"
@@ -42,4 +44,28 @@ public class EntitySeaplane : EntityBasicSeaplane
Radar = radar;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntitySeaplane), Speed.ToString(), Weight.ToString(), BodyColor.Name,
AdditionalColor.Name, LandingGear.ToString(), Radar.ToString()};
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntitySeaplane? CreateEntitySeaplane(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntitySeaplane))
{
return null;
}
return new EntitySeaplane(Convert.ToInt32(strs[1]),
Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]),
Convert.ToBoolean(strs[6]));
}
}

View File

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

@@ -46,10 +46,17 @@
labelCollectionName = new Label();
СomboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip1 = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@@ -59,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(СomboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(854, 0);
groupBoxTools.Location = new Point(854, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(180, 614);
groupBoxTools.Size = new Size(180, 590);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@@ -74,9 +81,9 @@
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonDelSeaplane);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Location = new Point(3, 366);
panelCompanyTools.Location = new Point(3, 361);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(174, 245);
panelCompanyTools.Size = new Size(174, 226);
panelCompanyTools.TabIndex = 9;
//
// buttonAddBasicSeaplane
@@ -95,7 +102,7 @@
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.FlatStyle = FlatStyle.Flat;
buttonRefresh.Location = new Point(0, 197);
buttonRefresh.Location = new Point(0, 183);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(174, 31);
buttonRefresh.TabIndex = 6;
@@ -105,7 +112,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(0, 97);
maskedTextBox.Location = new Point(0, 83);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(174, 23);
@@ -116,7 +123,7 @@
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.FlatStyle = FlatStyle.Flat;
buttonGoToCheck.Location = new Point(0, 162);
buttonGoToCheck.Location = new Point(0, 148);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(174, 29);
buttonGoToCheck.TabIndex = 5;
@@ -128,7 +135,7 @@
//
buttonDelSeaplane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelSeaplane.FlatStyle = FlatStyle.Flat;
buttonDelSeaplane.Location = new Point(0, 126);
buttonDelSeaplane.Location = new Point(0, 112);
buttonDelSeaplane.Name = "buttonDelSeaplane";
buttonDelSeaplane.Size = new Size(174, 30);
buttonDelSeaplane.TabIndex = 4;
@@ -242,12 +249,52 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(854, 614);
pictureBox.Size = new Size(854, 590);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1034, 24);
menuStrip1.TabIndex = 2;
menuStrip1.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.Filter = "txt file |*.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file |*.txt";
//
// FormPlaneCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
@@ -255,6 +302,8 @@
ClientSize = new Size(1034, 614);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormPlaneCollection";
Text = "Коллекция самолетов";
groupBoxTools.ResumeLayout(false);
@@ -263,7 +312,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -286,5 +338,11 @@
private RadioButton radioButtonMassive;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@@ -1,5 +1,10 @@
using ProjectSeaplane.CollectionGenericObjects;

using Microsoft.Extensions.Logging;
using ProjectSeaplane.CollectionGenericObjects;
using ProjectSeaplane.Drawnings;
using ProjectSeaplane.Exceptions;
using System.Windows.Forms;
namespace ProjectSeaplane;
/// <summary>
@@ -17,13 +22,16 @@ public partial class FormPlaneCollection : Form
/// </summary>
AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormPlaneCollection()
public FormPlaneCollection(ILogger<FormPlaneCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
@@ -54,19 +62,30 @@ public partial class FormPlaneCollection : Form
/// <param name="plane"></param>
private void SetPlane(DrawingBasicSeaplane plane)
{
if (_company == null || plane == null)
try
{
return;
}
if (_company == null || plane == null)
{
return;
}
if (_company + plane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
if (_company + plane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + plane.GetDataForSave());
}
}
else
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Выход за границы коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -89,14 +108,19 @@ public partial class FormPlaneCollection : Form
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -114,26 +138,34 @@ public partial class FormPlaneCollection : Form
DrawingBasicSeaplane? seaplane = null;
int counter = 100;
while (seaplane == null)
try
{
seaplane = _company.GetRandomObject();
counter--;
if (counter <= 0)
while (seaplane == null)
{
break;
seaplane = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
}
if (seaplane == null)
{
return;
}
if (seaplane == null)
{
return;
}
FormSeaplane form = new()
FormSeaplane form = new()
{
SetSeaplane = seaplane
};
form.ShowDialog();
}
catch (Exception ex)
{
SetSeaplane = seaplane
};
form.ShowDialog();
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
@@ -166,17 +198,27 @@ public partial class FormPlaneCollection : Form
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
try
{
collectionType = CollectionType.Massive;
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
else if (radioButtonList.Checked)
catch (Exception ex)
{
collectionType = CollectionType.List;
_logger.LogError("Ошибка: {Message}", ex.Message);
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
/// <summary>
/// Обновление списка в ListboxCollection
@@ -206,12 +248,20 @@ public partial class FormPlaneCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
try
{
return;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
/// <summary>
/// создание компании
@@ -243,5 +293,54 @@ public partial class FormPlaneCollection : Form
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
}

View File

@@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>132, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>271, 17</value>
</metadata>
</root>

View File

@@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Microsoft.Extensions.Configuration;
namespace ProjectSeaplane
{
internal static class Program
@@ -11,7 +16,30 @@ namespace ProjectSeaplane
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormPlaneCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider servicesProvider = services.BuildServiceProvider();
Application.Run(servicesProvider.GetRequiredService<FormPlaneCollection>());
}
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<FormPlaneCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile($"{pathNeed}serilog.json")
.Build())
.CreateLogger());
});
}
}
}
}

View File

@@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@@ -23,4 +34,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

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