5 Commits

Author SHA1 Message Date
04ad6e99cd лаба сдана 2024-05-13 12:17:02 +04:00
a0bc374e1b вроде готова к сдаче 2024-05-09 20:47:40 +04:00
61179daf0b лаба 7 почти готова 2024-05-09 14:47:31 +04:00
b89a2370f2 лаба принята 2024-04-29 12:25:09 +04:00
e31a0b24a5 готова к сдаче 2024-04-29 01:03:50 +04:00
21 changed files with 693 additions and 93 deletions

View File

@@ -1,4 +1,5 @@
using ProjectContainerShip.Drawnings;
using ProjectContainerShip.Exceptions;
namespace ProjectContainerShip.CollectionGenericObjects;
/// <summary>
@@ -34,7 +35,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
@@ -47,7 +48,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
@@ -72,6 +73,7 @@ public abstract class AbstractCompany
return company._collection?.Remove(position) ?? null;
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
@@ -95,8 +97,12 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningShip? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningShip? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception) { }
}
return bitmap;

View File

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

View File

@@ -1,4 +1,5 @@
using System;
using ProjectContainerShip.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -25,7 +26,19 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount
{
get => _maxCount;
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
@@ -37,42 +50,42 @@ 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)
{
if (Count == _maxCount) { return -1; }
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count || Count == _maxCount)
{
return -1;
}
_collection.Insert(position, obj);
if (position < 0 || position >= Count)
throw new PositionOutOfCollectionException(position);
if (Count == _maxCount)
throw new CollectionOverflowException(Count);
_collection.Insert(position, obj);
return position;
}
public T Remove(int position)
{
if (position >= Count || position < 0) return null;
T? obj = _collection[position];
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@@ -1,4 +1,6 @@
namespace ProjectContainerShip.CollectionGenericObjects;
using ProjectContainerShip.Exceptions;
namespace ProjectContainerShip.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@@ -14,8 +16,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@@ -32,6 +38,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@@ -42,24 +50,29 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
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)
{
return Insert(obj, 0);
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
@@ -84,17 +97,26 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
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;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@@ -1,4 +1,5 @@
using ProjectContainerShip.Drawnings;
using ProjectContainerShip.Exceptions;
namespace ProjectContainerShip.CollectionGenericObjects;
@@ -18,6 +19,11 @@ public class ShipSharingService : AbstractCompany
protected override void DrawBackground(Graphics g)
{
Color backgroundColor = Color.SkyBlue;
using (Brush brush = new SolidBrush(backgroundColor))
{
g.FillRectangle(brush, new Rectangle(0, 0, _pictureWidth, _pictureHeight));
}
Pen pen = new Pen(Color.Brown, 3);
int offsetX = 10, offsetY = -12;
int x = 1 + offsetX, y = _pictureHeight - _placeSizeHeight + offsetY;
@@ -29,7 +35,7 @@ public class ShipSharingService : AbstractCompany
{
numCols++;
g.DrawLine(pen, x, y, x + _placeSizeWidth / 2, y);
g.DrawLine(pen, x, y, x, y + _placeSizeHeight + 8);
g.DrawLine(pen, x, y, x, y + _placeSizeHeight + 4);
locCoord.Add(new Tuple<int, int>(x, y));
x += _placeSizeWidth + 2;
}
@@ -48,8 +54,12 @@ public class ShipSharingService : 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

@@ -1,4 +1,6 @@
using System;
using ProjectContainerShip.Drawnings;
using ProjectContainerShip.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -11,7 +13,7 @@ namespace ProjectContainerShip.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningShip
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@@ -24,6 +26,22 @@ public class StorageCollection<T>
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
@@ -86,4 +104,125 @@ public class StorageCollection<T>
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
using (StreamWriter sw = new StreamWriter(filename))
{
sw.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> kvpair in _storages)
{
// не сохраняем пустые коллекции
if (kvpair.Value.Count == 0)
continue;
sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
continue;
sb.Append(data);
sb.Append(_separatorItems);
}
sw.WriteLine(sb.ToString());
sb.Clear();
}
}
}
/// <summary>
/// Загрузка информации по кораблям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str == null || str.Length == 0)
throw new Exception("В файле нет данных");
if (str != _collectionKey.ToString())
throw new Exception("В файле неверные данные");
_storages.Clear();
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningShip() is T boat)
{
try
{
if (collection.Insert(boat) == -1)
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@@ -22,6 +22,16 @@ public class DrawningContainerShip : DrawningShip
EntityShip = new EntityContainerShip(speed, weight, bodyColor, additionalColor, crane, container);
}
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
/// <summary>
/// Конструктор через сущность
/// </summary>
/// <param name="ship">Объект класса-сущность</param>
public DrawningContainerShip(EntityShip entityShip) : base()
{
EntityShip = entityShip;
}
public override void DrawTransport(Graphics g)
{
if (EntityShip == null || EntityShip is not EntityContainerShip containerShip || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@@ -66,7 +66,7 @@ public class DrawningShip
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningShip()
protected DrawningShip()
{
_pictureWidth = null;
_pictureHeight = null;
@@ -96,6 +96,15 @@ public class DrawningShip
_pictureHeight = drawningShipHeight;
}
/// <summary>
/// Конструктор через сущность
/// </summary>
/// <param name="ship">Объект класса-сущность</param>
public DrawningShip(EntityShip entityShip) : base()
{
EntityShip = entityShip;
}
/// <summary>
/// Установка границ поля
/// </summary>

View File

@@ -0,0 +1,51 @@
using ProjectContainerShip.Entities;
namespace ProjectContainerShip.Drawnings;
public static class ExtentionDrawningShip
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningShip? CreateDrawningShip(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityShip? ship = EntityContainerShip.CreateEntityContainerShip(strs);
if (ship != null)
{
return new DrawningContainerShip(ship);
}
ship = EntityShip.CreateEntityShip(strs);
if (ship != null)
{
return new DrawningShip(ship);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningShip">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningShip drawningShip)
{
string[]? array = drawningShip?.EntityShip?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -37,4 +37,29 @@ public class EntityContainerShip : EntityShip
Crane = crane;
Container = container;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityContainerShip), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Crane.ToString(), Container.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityContainerShip? CreateEntityContainerShip(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityContainerShip))
{
return null;
}
return new EntityContainerShip(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

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

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 ProjectContainerShip.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 ProjectContainerShip.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,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip.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();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@@ -59,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(930, 0);
groupBoxTools.Location = new Point(935, 25);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(206, 638);
groupBoxTools.Size = new Size(206, 644);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@@ -242,19 +249,62 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 25);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(930, 638);
pictureBox.Size = new Size(935, 644);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1141, 25);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(50, 21);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(192, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(192, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// FormShipCollection
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1136, 638);
ClientSize = new Size(1141, 669);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormShipCollection";
Text = "Коллекция кораблей";
groupBoxTools.ResumeLayout(false);
@@ -263,7 +313,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -286,5 +339,11 @@
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@@ -1,5 +1,8 @@
using ProjectContainerShip.CollectionGenericObjects;
using ProjectContainerShip.Drawnings;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using ProjectContainerShip.Exceptions;
namespace ProjectContainerShip
@@ -19,15 +22,23 @@ namespace ProjectContainerShip
/// </summary>
private readonly StorageCollection<DrawningShip> _storageCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormShipCollection()
public FormShipCollection(ILogger<FormShipCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
#region Работа с компанией
/// <summary>
/// Выбор компании
/// </summary>
@@ -58,19 +69,25 @@ namespace ProjectContainerShip
/// <param name="boat"></param>
private void SetShip(DrawningShip? ship)
{
if (_company == null || ship == null)
try
{
return;
}
if (_company == null || ship == null)
{
return;
}
if (_company + ship != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
if (_company + ship != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + ship.GetDataForSave());
}
}
else
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show("В коллекции превышено допустимое количество элементов");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -81,25 +98,31 @@ namespace ProjectContainerShip
/// <param name="e"></param>
private void ButtonDelShip_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
throw new Exception("Входные данные отсутствуют");
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект удален");
}
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show("Не найден объект по позиции " + pos);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -117,24 +140,32 @@ namespace ProjectContainerShip
DrawningShip? ship = null;
int counter = 100;
while (ship == null)
try
{
ship = _company.GetRandomObject();
counter--;
if (counter <= 0)
while (ship == null)
{
break;
ship = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
}
if (ship == null)
if (ship == null)
{
return;
}
FormContainerShip form = new FormContainerShip();
form.SetShip = ship;
form.ShowDialog();
}
catch (Exception ex)
{
return;
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
FormContainerShip form = new FormContainerShip();
form.SetShip = ship;
form.ShowDialog();
}
/// <summary>
@@ -151,7 +182,8 @@ namespace ProjectContainerShip
pictureBox.Image = _company.Show();
}
#endregion
#region Работа с коллекцией
/// <summary>
/// Добавление коллекции
/// </summary>
@@ -162,6 +194,7 @@ namespace ProjectContainerShip
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
return;
}
CollectionType collectionType = CollectionType.None;
@@ -175,6 +208,7 @@ namespace ProjectContainerShip
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text);
RefreshListBoxItems();
}
@@ -207,12 +241,22 @@ namespace ProjectContainerShip
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());
RefreshListBoxItems();
_logger.LogInformation("Удалена коллекция: ", listBoxCollection.SelectedItem.ToString());
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
@@ -240,10 +284,59 @@ namespace ProjectContainerShip
case "Хранилище":
_company = new ShipSharingService(pictureBox.Width, pictureBox.Height, collection);
break;
default:
return;
}
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
#endregion
/// <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);
RefreshListBoxItems();
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);
}
}
}
}
}

View File

@@ -117,6 +117,15 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>131, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>276, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>79</value>
</metadata>

View File

@@ -145,9 +145,9 @@ public partial class FormShipConfig : Form
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_ship?.EntityShip is EntityContainerShip _catamaran)
if (_ship?.EntityShip is EntityContainerShip _containerShip)
{
_catamaran.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
_containerShip.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();

View File

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

View File

@@ -8,6 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@@ -23,4 +33,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appSetting.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": {
"Applicatoin": "Sample"
}
}
}