7 лаб. работа (не доделана)

This commit is contained in:
Азамат Иштуганов 2024-05-07 02:08:20 +04:00
parent 077f39a55a
commit 497eb540fd
10 changed files with 217 additions and 59 deletions

View File

@ -1,4 +1,6 @@

using MotorBoat.Exceptions;
namespace MotorBoat.CollectionGenericObjects;
/// <summary>
@ -45,34 +47,30 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
public T? Get(int position)
{
if (position < 0 || position >= Count)
{
return null;
}
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException();
return _collection[position];
}
public int Insert(T obj)
{
if (Count + 1 > _maxCount) return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (Count + 1 > _maxCount) return -1;
if (position < 0 || position > Count) return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return 1;
return position;
}
public T? Remove(int position)
{
if (position < 0 || position > Count) return null;
T? temp = _collection[position];
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T? obj = _collection[position];
_collection.RemoveAt(position);
return temp;
return obj;
}
public IEnumerable<T?> GetItems()

View File

@ -1,4 +1,6 @@

using MotorBoat.Exceptions;
namespace MotorBoat.CollectionGenericObjects;
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
@ -39,7 +41,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
public T? Get(int position)
{
if (position < 0 || position >= Count) return null;
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
return _collection[position];
}
public int Insert(T obj)
@ -52,15 +54,19 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
throw new CollectionOverflowException();
}
public int Insert(T obj, int position)
{
if (position >= Count || position < 0) return -1;
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException();
}
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
int temp = position + 1;
while (temp < Count)
@ -86,7 +92,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
public T? Remove(int position)
{
if (position >= Count || position < 0) return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
if (_collection[position] == null) throw new ObjectNotFoundException();
T? myObject = _collection[position];
_collection[position] = null;
return myObject;

View File

@ -1,4 +1,5 @@
using MotorBoat.Drawnings;
using MotorBoat.Exceptions;
namespace MotorBoat.CollectionGenericObjects;
@ -90,15 +91,15 @@ public class StorageCollection<T>
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// Сохранение информации по лодкам в хранилище в файл
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
@ -134,31 +135,29 @@ public class StorageCollection<T>
}
}
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// Загрузка информации по лодкам в хранилище из файла
/// </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 FileNotFoundException("Файл не существует");
}
using (StreamReader reader = new(filename))
{
string line = reader.ReadLine();
if (line == null || line.Length == 0)
{
return false;
throw new ArgumentException("В файле нет данных");
}
if (!line.Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
return false;
throw new InvalidDataException("В файле неверные данные");
}
_storages.Clear();
while ((line = reader.ReadLine()) != null)
@ -170,28 +169,31 @@ public class StorageCollection<T>
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
}
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType) ??
throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]); ;
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBoat() is T boat)
{
try
{
if (collection.Insert(boat) == -1)
{
return false;
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
return true;
}
/// <summary>

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 MotorBoat.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 MotorBoat.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 MotorBoat.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 MotorBoat.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using MotorBoat.CollectionGenericObjects;
using MotorBoat.Drawnings;
using MotorBoat.Exceptions;
namespace MotorBoat;
@ -16,13 +18,16 @@ public partial class FormBoatCollection : Form
/// Компания
/// </summary>
private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormBoatCollection()
public FormBoatCollection(ILogger<FormBoatCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
/// Выбор компании
@ -60,15 +65,17 @@ public partial class FormBoatCollection : Form
{
return;
}
if (_company + boat != -1)
try
{
int addingObject = (_company + boat);
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {boat.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
else
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
}
/// <summary>
@ -80,6 +87,7 @@ public partial class FormBoatCollection : Form
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
_logger.LogWarning("Удаление объекта из несуществующей коллекции");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
@ -88,14 +96,22 @@ public partial class FormBoatCollection : Form
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
try
{
object decrementObject = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален по позиции {pos}");
pictureBox.Image = _company.Show();
}
else
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show("Объект не найден ");
_logger.LogWarning($"Удаление не найденного объекта в позиции {pos} ");
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Удаление вне рамках коллекции");
_logger.LogWarning($"Удаление объекта за пределами коллекции {pos} ");
}
}
/// <summary>
@ -112,14 +128,20 @@ public partial class FormBoatCollection : Form
DrawningBoat? boat = null;
int counter = 100;
while (boat == null)
{
try
{
boat = _company.GetRandomObject();
}
catch (ObjectNotFoundException)
{
counter--;
if (counter <= 0)
{
break;
}
}
}
if (boat == null)
{
return;
@ -154,6 +176,7 @@ public partial class FormBoatCollection : Form
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не заполненная коллекция");
return;
}
CollectionType collectionType = CollectionType.None;
@ -166,6 +189,7 @@ public partial class FormBoatCollection : Form
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}");
RerfreshListBoxItems();
}
/// <summary>
@ -182,15 +206,17 @@ public partial class FormBoatCollection : Form
if (listBoxCollection.SelectedIndex < 0)
{
MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Удаление невыбранной коллекции");
return;
}
string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show("Удалить коллекцию?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation($"Удалена коллекция: {name}");
RerfreshListBoxItems();
}
/// <summary>
@ -218,6 +244,7 @@ public partial class FormBoatCollection : Form
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Создание компании невыбранной коллекции");
return;
}
ICollectionGenericObjects<DrawningBoat>? collection =
@ -225,6 +252,7 @@ public partial class FormBoatCollection : Form
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
_logger.LogWarning("Не удалось инициализировать коллекцию");
return;
}
switch (comboBoxSelectorCompany.Text)
@ -246,15 +274,16 @@ public partial class FormBoatCollection : 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);
}
}
}
@ -268,14 +297,17 @@ 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);
_logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
RerfreshListBoxItems();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось сохранить", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}

View File

@ -8,6 +8,12 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.10" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
namespace MotorBoat
{
internal static class Program
@ -8,8 +13,33 @@ namespace MotorBoat
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormBoatCollection());
}
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider =
services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormBoatCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBoatCollection>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "serilog.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}Û

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": "MotorBoat"
}
}
}