7 лабораторная работа

This commit is contained in:
Arslan 2024-04-29 08:29:24 +04:00
parent 227e8136f7
commit 69370b211a
10 changed files with 221 additions and 190 deletions

View File

@ -1,4 +1,5 @@
using ProjectFighterJet.CollectionGenericObjects;
using ProjectFighterJet.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -57,33 +58,28 @@ where T : class
}
public int Insert(T obj)
{
if (Count <= _maxCount)
{
// TODO выброс ошибки если переполнение
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
return -1;
}
public int Insert(T obj, int position)
{
if (Count < _maxCount && position >= 0 && position < _maxCount)
{
// TODO выброс ошибки если переполнение
// TODO выброс ошибки если за границу
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
}
return -1;
}
public T Remove(int position)
{
T temp = _collection[position];
if (position >= 0 && position < _maxCount)
{
// TODO если выброс за границу
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return temp;
return obj;
}
return null;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)

View File

@ -1,4 +1,5 @@
using ProjectFighterJet.Drawnings;
using ProjectFighterJet.Exceptions;
namespace ProjectFighterJet.CollectionGenericObjects;
@ -65,12 +66,14 @@ where T : class
}
index++;
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position >= _collection.Length || position < 0) return -1;
// TODO выброс ошибки если переполнение
// TODO выброс ошибки если выход за границу
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
_collection[position] = obj;
@ -84,7 +87,7 @@ where T : class
_collection[index] = obj;
return index;
}
index++;
++index;
}
index = position - 1;
while (index >= 0)
@ -94,17 +97,20 @@ where T : class
_collection[index] = obj;
return index;
}
index--;
--index;
}
return -1;
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
if (position >= _collection.Length || position < 0) return null;
T temp = _collection[position];
// TODO выброс ошибки если выход за границу
// TODO выброс ошибки если объект пустой
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 temp;
return obj;
}
public IEnumerable<T?> GetItems()

View File

@ -6,6 +6,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Text;
using static System.Runtime.InteropServices.JavaScript.JSType;
using ProjectFighterJet.Exceptions;
namespace ProjectFighterJet.CollectionGenericObjects;
@ -90,12 +91,12 @@ where T : DrawningJet
/// Сохранение информации по автомобилям в хранилище в файл
/// </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("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
@ -106,19 +107,18 @@ where T : DrawningJet
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
writer.Write(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);
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
@ -126,85 +126,40 @@ where T : DrawningJet
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
writer.Write(data);
writer.Write(_separatorItems);
}
writer.Write(sb);
}
}
//if (_storages.Count == 0)
//{
// return false;
//}
//if (File.Exists(filename))
//{
// File.Delete(filename);
//}
//StringBuilder sb = new();
//sb.Append(_collectionKey);
//foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
//{
// 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);
// }
//}
//using FileStream fs = new(filename, FileMode.Create);
//byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
//fs.Write(info, 0, info.Length);
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 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 = "";
while ((strs = fs.ReadLine()) != null)
{
//по идее этого произойти не должно
//if (strs == null)
//{
// return false;
//}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
@ -214,73 +169,29 @@ where T : DrawningJet
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?.CreateDrawningJet() is T jet)
{
try
{
if (collection.Insert(jet) == -1)
{
return false;
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
//string bufferTextFromFile = "";
//using (FileStream fs = new(filename, FileMode.Open))
//{
// byte[] b = new byte[fs.Length];
// UTF8Encoding temp = new(true);
// while (fs.Read(b, 0, b.Length) > 0)
// {
// bufferTextFromFile += temp.GetString(b);
// }
//}
//string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
//if (strs == null || strs.Length == 0)
//{
// return false;
//}
//if (!strs[0].Equals(_collectionKey))
//{
// //если нет такой записи, то это не те данные
// return false;
//}
//_storages.Clear();
//foreach (string data in strs)
//{
// string[] record = data.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)
// {
// return false;
// }
// collection.MaxCount = Convert.ToInt32(record[2]);
// string[] set = record[3].Split(_separatorItems,
// StringSplitOptions.RemoveEmptyEntries);
// foreach (string elem in set)
// {
// if (elem?.CreateDrawningShip() is T ship)
// {
// if (collection.Insert(ship) == -1)
// {
// return false;
// }
// }
// }
// _storages.Add(record[0], collection);
//}
//return true;
}
}
/// <summary>

View File

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectFighterJet.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 ProjectFighterJet.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 ProjectFighterJet.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 ProjectFighterJet.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectFighterJet.CollectionGenericObjects;
using ProjectFighterJet.Drawnings;
using ProjectFighterJet.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -26,10 +28,15 @@ public partial class FormJetCollection : Form
/// <summary>
/// Конструктор
/// </summary>
public FormJetCollection()
private readonly ILogger _logger;
public FormJetCollection(ILogger<FormJetCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
/// Выбор компании
@ -48,14 +55,24 @@ public partial class FormJetCollection : Form
private void SetJet(DrawningJet jet)
{
try
{
if (_company == null || jet == null)
{
return;
}
if (_company + jet != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + jet.GetDataForSave());
}
else
}
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
@ -99,15 +116,19 @@ public partial class FormJetCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
int tempSize = FighterJetSharingService.getAmountOfObjects();
try
{
if (_company - pos != null)
{
MessageBox.Show("Объект удалён");
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
else
}
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
@ -123,6 +144,8 @@ public partial class FormJetCollection : Form
}
DrawningJet? jet = null;
int counter = 100;
try
{
while (jet == null)
{
jet = _company.GetRandomObject();
@ -132,16 +155,18 @@ public partial class FormJetCollection : Form
break;
}
}
if (jet == null)
{
return;
}
FormFighterJet form = new()
{
Setjet = jet
};
form.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
@ -164,6 +189,8 @@ public partial class FormJetCollection : Form
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
@ -175,6 +202,12 @@ public partial class FormJetCollection : Form
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
@ -239,15 +272,16 @@ public partial class FormJetCollection : 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);
}
}
}
@ -262,16 +296,17 @@ public partial class FormJetCollection : 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

@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using NLog.Extensions.Logging;
namespace ProjectFighterJet
{
internal static class Program
@ -11,7 +16,21 @@ namespace ProjectFighterJet
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormJetCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormJetCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormJetCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}
}

View File

@ -11,6 +11,9 @@
<ItemGroup>
<PackageReference Include="EntityFramework" Version="5.0.0" />
<PackageReference Include="EntityFramework.ru" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.9" />
</ItemGroup>
<ItemGroup>

View File

@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>