ISEbd-12_Frolova.A.S._LabWork07_Simple #9

Closed
Fr_Alyona wants to merge 3 commits from LabWork07 into LabWork06
12 changed files with 365 additions and 151 deletions

View File

@ -1,4 +1,5 @@
using ProjectCatamaran.Drawnings;
using ProjectCatamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -32,7 +33,8 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
@ -88,8 +90,15 @@ private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningBoat? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningBoat? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{ }
catch (PositionOutOfCollectionException e)
{ }
}
return bitmap;
}

View File

@ -1,4 +1,5 @@
using ProjectCatamaran.Drawnings;
using ProjectCatamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -27,14 +28,14 @@ public class BoatHarborService : AbstractCompany
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
Pen pen = new(Color.Black, 4);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
Pen pen = new(Color.Black, 2);
for (int i = 0; i < width + 1; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
for (int j = 0; j < height + 1; ++j)
{
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight + 5, i * _placeSizeWidth + _placeSizeWidth - 90, j * _placeSizeHeight + 5);
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight);
g.DrawLine(pen, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight - _placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth,0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight + 5);
}
}
@ -48,23 +49,27 @@ public class BoatHarborService : 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 + 10, curHeight * _placeSizeHeight + 5);
}
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException e) { }
if (curWidth < width - 1)
curWidth++;
else
{
curWidth = 0;
curHeight--;
}
if (curHeight < 0)
{
return;
}
}
curWidth++;
else
{
curWidth = 0;
curHeight--;
}
if (curHeight < 0)
{
return;
}
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectCatamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -31,39 +32,30 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
return _collection[position];
}
return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
if (Count <= _maxCount)
{
_collection.Add(obj);
return Count;
}
return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (Count < _maxCount && position >= 0 && position < _maxCount)
{
_collection.Insert(position, obj);
return position;
}
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)
{
T temp = _collection[position];
if (position >= 0 && position < _maxCount)
{
_collection.RemoveAt(position);
return temp;
}
return null;
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()

View File

@ -1,4 +1,5 @@
using System;
using ProjectCatamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -53,67 +54,77 @@ namespace ProjectCatamaran.CollectiongGenericObjects;
}
public T? Get(int position)
{
// проверка позиции
if (position >= _collection.Length || position < 0)
{
return null;
}
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
{
// вставка в свободное место набора
int index = 0;
while (index < _collection.Length)
// вставка в свободное место набора
for (int i = 0; i < Count; i++)
{
if (_collection[index] == null)
if (_collection[i] == null)
{
_collection[index] = obj;
return index;
_collection[i] = obj;
return i;
}
index++;
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
// проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (position >= _collection.Length || position < 0)
{ return -1; }
if (_collection[position] == null)
if (_collection[position] != null)
{
_collection[position] = obj;
return position;
}
int index;
for (index = position + 1; index < _collection.Length; ++index)
{
if (_collection[index] == null)
bool pushed = false;
int index;
for (index = position + 1; index < _collection.Length; index++)
{
_collection[position] = obj;
return position;
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
for (index = position - 1; index >= 0; --index)
{
if (_collection[index] == null)
if (!pushed)
{
_collection[position] = obj;
return position;
for (index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
}
}
return -1;
_collection[position] = obj;
return position;
}
public T Remove(int position)
public T? Remove(int position)
{
if (position >= _collection.Length || position < 0)
{ return null; }
T DrawningBoat = _collection[position];
// проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T temp = _collection[position];
_collection[position] = null;
return DrawningBoat;
return temp;
}
public IEnumerable<T?> GetItems()

View File

@ -1,9 +1,11 @@
using ProjectCatamaran.Drawnings;
using ProjectCatamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace ProjectCatamaran.CollectiongGenericObjects;
@ -93,12 +95,12 @@ 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 на его более подходящих наследников
}
@ -144,7 +146,6 @@ public class StorageCollection<T>
}
}
return true;
}
@ -153,11 +154,11 @@ 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))
@ -166,7 +167,7 @@ public class StorageCollection<T>
string? str;
str = sr.ReadLine();
if (str != _collectionKey.ToString())
return false;
throw new Exception("В файле нет данных");
_storages.Clear();
@ -183,7 +184,7 @@ 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]);
@ -191,17 +192,24 @@ public class StorageCollection<T>
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBoat() is T Truck)
if (elem?.CreateDrawningBoat() is T boat)
{
if (collection.Insert(Truck) == -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);
}
}
return true;
}
/// <summary>

View File

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

@ -1,5 +1,7 @@
using ProjectCatamaran.CollectiongGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectCatamaran.CollectiongGenericObjects;
using ProjectCatamaran.Drawnings;
using ProjectCatamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -9,6 +11,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace ProjectCatamaran;
@ -22,12 +25,19 @@ public partial class FormBoatCollection : Form
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company;
private AbstractCompany? _company = null;
public FormBoatCollection()
/// <summary>
/// Конструктор
/// </summary>
private readonly ILogger _logger;
public FormBoatCollection(ILogger<FormBoatCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
@ -60,19 +70,22 @@ public partial class FormBoatCollection : Form
/// <param name="boat"></param>
private void SetBoat(DrawningBoat boat)
{
if (_company == null || boat == null)
if (_company == null || boat == null)
{
return;
}
try
{
return;
}
if (_company + boat != -1)
{
MessageBox.Show("объект добавлен");
var res = _company + boat;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBoxBoat.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("не удалось добавить объект");
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -96,14 +109,18 @@ public partial class FormBoatCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
try
{
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBoxBoat.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -121,24 +138,32 @@ public partial class FormBoatCollection : Form
DrawningBoat? boat = null;
int counter = 100;
while (boat == null)
try
{
boat = _company.GetRandomObject();
counter--;
if (counter <= 0)
while (boat == null)
{
break;
boat = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (boat == null)
{
return;
}
FormCatamaran form = new()
{
SetBoat = boat
};
form.ShowDialog();
}
if (boat == null)
catch (Exception ex)
{
return;
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
FormCatamaran form = new()
{
SetBoat = boat
};
form.ShowDialog();
}
/// <summary>
@ -170,16 +195,25 @@ public partial class FormBoatCollection : 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();
}
@ -196,13 +230,20 @@ public partial class FormBoatCollection : 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>
@ -261,13 +302,16 @@ public partial class FormBoatCollection : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
_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);
}
}
}
@ -281,14 +325,18 @@ public partial class FormBoatCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_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);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}

View File

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

View File

@ -8,6 +8,17 @@
<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="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="6.0.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +34,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Catamaran"
}
}
}