PIBD-11 Shipilov N.S. Seaplane Simple LabWork7 #7

Closed
NikitaShipilov wants to merge 2 commits from LabWork7 into LabWork6
15 changed files with 253 additions and 143 deletions
Showing only changes of commit 5414ff55a1 - Show all commits

View File

@ -1,4 +1,6 @@
namespace ProjectSeaplane.CollectionGenericObjects;
using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
@ -33,26 +35,26 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= Count || position < 0) 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 (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;
}
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;

View File

@ -1,4 +1,6 @@
namespace ProjectSeaplane.CollectionGenericObjects;
using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane.CollectionGenericObjects;
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
@ -36,9 +38,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection = Array.Empty<T?>();
}
public T? Get(int position)
public T Get(int position)
{
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];
}
@ -54,12 +57,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
++index;
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position >= _collection.Length || position < 0)
return -1;
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
_collection[position] = obj;
@ -85,12 +87,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
--index;
}
return -1;
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
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;

View File

@ -32,11 +32,12 @@ internal class PlaneSharingService : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection.Get(i) != null)
try
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth, curHeight * _placeSizeHeight + 4);
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(_placeSizeWidth * curWidth, curHeight * _placeSizeHeight + 4);
}
catch (Exception) { }
if (curWidth > 0)
curWidth--;
else

View File

@ -1,4 +1,5 @@
using ProjectSeaplane.Drawings;
using ProjectSeaplane.Exceptions;
using System.Text;
namespace ProjectSeaplane.CollectionGenericObjects;
@ -78,11 +79,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("В хранилище отсутствуют коллекции для сохранения");
Review

Требовалось заменить класс Exception на его более подходящих наследников

Требовалось заменить класс Exception на его более подходящих наследников
}
if (File.Exists(filename))
{
@ -119,8 +120,6 @@ public class StorageCollection<T>
}
}
return true;
}
/// <summary>
@ -128,22 +127,22 @@ 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 fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
return false;
throw new Exception("В файле неверные данные");
}
_storages.Clear();
string strs = "";
@ -158,23 +157,29 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningPlane() is T ship)
if (elem?.CreateDrawningPlane() is T plane)
{
if (collection.Insert(ship) == -1)
try
{
return false;
if (collection.Insert(plane) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}

View File

@ -49,9 +49,9 @@ public class DrawingPlane
_drawingPlaneHeight = drawingSeaplaneHeight;
}
public DrawingPlane(EntityPlane ship) : this()
public DrawingPlane(EntityPlane plane) : this()
{
EntityPlane = new EntityPlane(ship.Speed, ship.Weight, ship.BodyColor);
EntityPlane = new EntityPlane(plane.Speed, plane.Weight, plane.BodyColor);
}
public bool SetPictureSize(int width, int height)

View File

@ -14,9 +14,9 @@ public class DrawingSeaplane : DrawingPlane
EntityPlane = new EntitySeaplane(speed, weight, bodyColor, additionalColor, floats, inflatableBoat);
}
public DrawingSeaplane(EntitySeaplane ship) : base(190, 85)
public DrawingSeaplane(EntitySeaplane plane) : base(190, 85)
{
EntityPlane = new EntitySeaplane(ship.Speed, ship.Weight, ship.BodyColor, ship.AdditionalColor, ship.Floats, ship.InflatableBoat);
EntityPlane = new EntitySeaplane(plane.Speed, plane.Weight, plane.BodyColor, plane.AdditionalColor, plane.Floats, plane.InflatableBoat);
}
public override void DrawTransport(Graphics g)

View File

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

@ -66,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(764, 24);
groupBoxTools.Location = new Point(677, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(200, 603);
groupBoxTools.Size = new Size(200, 583);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -98,7 +98,7 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(3, 97);
maskedTextBoxPosition.Location = new Point(3, 50);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(182, 23);
@ -107,7 +107,7 @@
//
// buttonRefresh
//
buttonRefresh.Location = new Point(3, 216);
buttonRefresh.Location = new Point(3, 197);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(182, 41);
buttonRefresh.TabIndex = 6;
@ -117,7 +117,7 @@
//
// buttonDelPlane
//
buttonDelPlane.Location = new Point(3, 126);
buttonDelPlane.Location = new Point(3, 107);
buttonDelPlane.Name = "buttonDelPlane";
buttonDelPlane.Size = new Size(182, 41);
buttonDelPlane.TabIndex = 4;
@ -127,7 +127,7 @@
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(3, 173);
buttonGoToCheck.Location = new Point(3, 154);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(182, 41);
buttonGoToCheck.TabIndex = 5;
@ -244,7 +244,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(764, 603);
pictureBox.Size = new Size(677, 583);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -253,7 +253,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(964, 24);
menuStrip.Size = new Size(877, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
@ -292,7 +292,7 @@
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(964, 627);
ClientSize = new Size(877, 607);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);

View File

@ -1,5 +1,7 @@
using ProjectSeaplane.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectSeaplane.CollectionGenericObjects;
using ProjectSeaplane.Drawings;
using ProjectSeaplane.Exceptions;
using System.Windows.Forms;
namespace ProjectSeaplane;
@ -10,10 +12,14 @@ public partial class FormSeaplaneCollection : Form
private AbstractCompany? _company = null;
public FormSeaplaneCollection()
private readonly ILogger _logger;
public FormSeaplaneCollection(ILogger<FormSeaplaneCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
@ -30,67 +36,27 @@ public partial class FormSeaplaneCollection : Form
private void SetPlane(DrawingPlane? plane)
{
if (_company == null || plane == null)
try
{
return;
}
if (_company + plane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawingPlane drawningPlane;
switch (type)
{
case nameof(DrawingPlane):
drawningPlane = new DrawingPlane(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawingSeaplane):
drawningPlane = new DrawingSeaplane(random.Next(100, 300), random.Next(1000, 3000),
GetColor(random), GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
if (_company == null || plane == null)
{
return;
}
if (_company + plane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + plane.GetDataForSave());
}
}
if (_company + drawningPlane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
private void buttonDelPlane_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
@ -104,14 +70,19 @@ public partial class FormSeaplaneCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.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);
}
}
@ -124,26 +95,27 @@ public partial class FormSeaplaneCollection : Form
DrawingPlane? plane = null;
int counter = 100;
while (plane == null)
try
{
plane = _company.GetRandomObject();
counter--;
if (counter <= 0)
while (plane == null)
{
break;
plane = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
FormSeaplane form = new()
{
SetPlane = plane
};
form.ShowDialog();
}
if (plane == null)
catch (Exception ex)
{
return;
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
FormSeaplane form = new()
{
SetPlane = plane
};
form.ShowDialog();
}
private void buttonRefresh_Click(object sender, EventArgs e)
@ -164,18 +136,25 @@ public partial class FormSeaplaneCollection : Form
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();
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
@ -185,12 +164,20 @@ public partial class FormSeaplaneCollection : 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();
}
private void RerfreshListBoxItems()
@ -204,7 +191,6 @@ public partial class FormSeaplaneCollection : Form
listBoxCollection.Items.Add(colName);
}
}
}
private void buttonCreateCompany_Click(object sender, EventArgs e)
@ -237,15 +223,16 @@ public partial class FormSeaplaneCollection : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@ -254,16 +241,17 @@ public partial class FormSeaplaneCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}

View File

@ -126,4 +126,7 @@
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>255, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</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,31 @@ 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 FormSeaplaneCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormSeaplaneCollection>());
}
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<FormSeaplaneCollection>()
.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.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.9" />
<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>

View File

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