ISEbd-12_Osyagina_A.A._Simple_LabWork07 #7

Closed
Osyagina_Anna wants to merge 5 commits from LabWork07 into LabWork06
10 changed files with 288 additions and 168 deletions
Showing only changes of commit 83c9dfd598 - Show all commits

View File

@ -1,4 +1,5 @@
using System;
using ProjectMotorboat.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -49,39 +50,36 @@ where T : class
public T? Get(int position)
{
// TODO проверка позиции
if (position >= Count || position < 0) return null;
//TODO выброс ошибки если выход за границу
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора
if (Count + 1 > _maxCount) return -1;
// TODO выброс ошибки если переполнение
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
if (Count + 1 > _maxCount) return -1;
if (position < 0 || position > Count) return -1;
// TODO выброс ошибки если переполнение
// TODO выброс ошибки если за границу
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)
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из списка
if (position < 0 || position > Count) return null;
T? pos = _collection[position];
// TODO если выброс за границу
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return pos;
return obj;
}
public IEnumerable<T> GetItems()

View File

@ -1,5 +1,7 @@

using ProjectMotorboat.Exceptions;
namespace ProjectMotorboat.CollectionGenericObjects;
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
@ -38,70 +40,68 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection = Array.Empty<T?>();
}
public T? Get(int position)
public T Get(int position)
{
if (position < 0 || position >= _collection.Length)
{
return null;
}
// TODO выброс ошибки если выход за границу
// TODO выброс ошибки если объект пустой
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)
{
for (int i = 0; i < _collection.Length; i++)
// TODO выброс ошибки если переполнение
int index = 0;
while (index < _collection.Length)
{
if (_collection[i] == null)
if (_collection[index] == null)
{
_collection[i] = obj;
return i;
_collection[index] = obj;
return index;
}
++index;
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= _collection.Length) { return position; }
// TODO выброс ошибки если выход за границу
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
else
int index = position + 1;
while (index < _collection.Length)
{
for (int i = position + 1; i < _collection.Length; i++)
if (_collection[index] == null)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
for (int i = position - 1; i >= 0; i--)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
_collection[index] = obj;
return index;
}
index++;
}
return -1;
index = position - 1;
while (index >= 0)
{
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
index--;
}
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
if (position < 0 || position >= _collection.Length)
{
return null;
}
T? obj = _collection[position];
// TODO выброс ошибки если объект пустой
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T removeObj = _collection[position];
_collection[position] = null;
return obj;
return removeObj;
}
public IEnumerable<T> GetItems()

View File

@ -1,4 +1,5 @@
using ProjectMotorboat.Drownings;
using ProjectMotorboat.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -23,8 +24,6 @@ public class StorageCollection<T>
public void AddCollection(string name, CollectionType collectionType)
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (name == null || _storages.ContainsKey(name)) { return; }
switch (collectionType)
@ -66,22 +65,20 @@ public class StorageCollection<T>
private readonly string _separatorItems = ";";
/// <summary>
/// Сохранение информации в хранилище в файл
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
Review

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

Требовалось заменить класс Exception на его более подходящих наследников
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
@ -89,7 +86,6 @@ public class StorageCollection<T>
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
@ -115,35 +111,35 @@ 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 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)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
@ -153,23 +149,30 @@ 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?.CreateDrawningBoat() is T militaryAircraft)
if (elem?.CreateDrawningBoat() is T track)
{
if (collection.Insert(militaryAircraft) == -1)
try
{
return false;
if (collection.Insert(track) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMotorboat.Exceptions;
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество count" + 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 ProjectMotorboat.Exceptions;
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("В коллекции превышено допустимое количество count" + 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,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMotorboat.Exceptions;
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("В коллекции превышено допустимое количество count" + 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,84 +1,66 @@
using ProjectMotorboat.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectMotorboat.CollectionGenericObjects;
using ProjectMotorboat.Drownings;
using ProjectMotorboat.Exceptions;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace ProjectMotorboat;
/// <summary>
/// Форма работы с компанией и ее коллекцией
/// </summary>
public partial class FormBoatCollection : Form
{
private readonly StorageCollection<DrawningBoat> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Конструктор
/// </summary>
public FormBoatCollection()
private readonly ILogger _logger;
public FormBoatCollection(ILogger<FormBoatCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Добавление обычного автомобиля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddBoat_Click(object sender, EventArgs e)
{
FormBoatConfig form = new();
// TODO передать метод
form.Show();
form.AddEvent(SetBoat);
form.Show();
}
private void SetBoat(DrawningBoat? boat)
{
if (_company == null || boat == null)
try
{
return;
if (_company == null || boat == null)
{
return;
}
if (_company + boat != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + boat.GetDataForSave());
}
}
if (_company + boat != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveBoat_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
@ -92,22 +74,23 @@ public partial class FormBoatCollection : Form
}
int pos = Convert.ToInt32(maskedTextBox.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);
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
@ -117,33 +100,31 @@ 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;
}
}
FormMotorboat Form = new()
{
SetBoat = boat
};
Form.ShowDialog();
}
catch (Exception ex)
if (boat == null)
{
return;
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
FormMotorboat form = new()
{
SetBoat = boat
};
form.ShowDialog();
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
@ -162,33 +143,53 @@ public partial class FormBoatCollection : 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)
{
if (listBoxCollection.SelectedItem == null)
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
try
{
return;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void RerfreshListBoxItems()
@ -234,13 +235,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);
}
}
}
@ -249,15 +253,20 @@ 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,3 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace ProjectMotorboat
{
internal static class Program
@ -10,8 +14,21 @@ namespace ProjectMotorboat
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ServiceCollection services = new();
ApplicationConfiguration.Initialize();
Application.Run(new FormBoatCollection());
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormBoatCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBoatCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}
}

View File

@ -8,4 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.3.2" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.10" />
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>