This commit is contained in:
elizaveta 2024-06-14 06:27:23 +04:00
parent 8f7affcd70
commit 43ba6f6d5f
11 changed files with 357 additions and 198 deletions

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.Exceptions;
namespace Tank.CollectionGenericObjects;
@ -11,6 +12,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : clas
private readonly List<T?> _collection;
private int _maxCount;
public int Count => _collection.Count;
public CollectionType GetCollectionType => CollectionType.List;
public int MaxCount
{
@ -24,8 +26,6 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : clas
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
@ -36,40 +36,33 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : clas
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
else
{
return null;
}
}
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 (position < 0 || position >= Count || Count == _maxCount)
{
return -1;
}
if (position < 0 || position >= Count)
throw new PositionOutOfCollectionException(position);
if (Count == _maxCount)
throw new CollectionOverflowException(Count);
_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);
_collection.RemoveAt(position);
return obj;
}

View File

@ -1,4 +1,6 @@
using Tank.CollectionGenericObjects;
using Tank.Exceptions;
namespace Tank.CollectionGenericObjects;
/// <summary>
@ -8,10 +10,8 @@ namespace Tank.CollectionGenericObjects;
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int MaxCount
{
get
@ -24,16 +24,15 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
Array.Resize(ref _collection, value - 9);
}
else
{
_collection = new T?[value];
_collection = new T?[value - 9];
}
}
}
}
public int Count => _collection.Length;
public CollectionType GetCollectionType => CollectionType.Massive;
@ -45,19 +44,21 @@ 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)
if (position < 0 || position >= _collection.Length)
{
return _collection[position];
throw new PositionOutOfCollectionException();
}
return null;
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position); //////////////
}
return _collection[position];
}
public int Insert(T obj)
{
// вставка в свободное место набора
for (int i = 0; i < _collection.Length; i++)
{
if (_collection[i] == null)
@ -66,76 +67,62 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
// проверка позиции
if (position < 0 || position >= _collection.Length)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
// проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
if (_collection[position] != null)
if (_collection[position] == null)
{
bool pushed = false;
for (int index = position + 1; index < _collection.Length; index++)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
return position;
}
}
// вставка
_collection[position] = obj;
return position;
}
else
{
for (int i = position; i < _collection.Length; ++i) //ищем свободное место справа
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
for (int i = 0; i < position; ++i) // иначе слева
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
}
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
// проверка позиции
if (position < 0 || position >= _collection.Length)
throw new PositionOutOfCollectionException(position);
T? obj = _collection[position];
if (_collection[position] == null)
{
return null;
throw new ObjectNotFoundException(position);
}
if (_collection[position] == null) return null;
T? temp = _collection[position];
if (_collection[position] != null)
{
_collection[position] = null;
return temp;
}
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; i++)
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}

View File

@ -1,6 +1,8 @@
using Tank.CollectionGenericObjects;
using System.Text;
using Tank.CollectionGenericObjects;
using Tank.Drawnings;
using Tank.Drowings;
using Tank.Exceptions;
namespace Tank.CollectionGenericObjects;
@ -99,36 +101,32 @@ 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("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter sw = new(fs);
sw.Write(_collectionKey);
StringBuilder sb = new();
sb.Append(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
sw.Write(Environment.NewLine);
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sw.Write(value.Key);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.GetCollectionType);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.MaxCount);
sw.Write(_separatorForKeyValue);
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;
@ -136,44 +134,40 @@ public class StorageCollection<T>
{
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);
}
sw.Write(data);
sw.Write(_separatorItems);
}
}
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 FileStream fs = new(filename, FileMode.Open);
using StreamReader sr = new(fs);
string str = sr.ReadLine();
using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.Equals(_collectionKey))
{
return false;
}
throw new Exception("В файле нет данных");
if (str != _collectionKey.ToString())
throw new Exception("В файле неверные данные");
_storages.Clear();
while (!sr.EndOfStream)
while ((str = sr.ReadLine()) != null)
{
string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4)
{
continue;
@ -182,22 +176,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]);
collection.MaxCount = Convert.ToInt32(record[2]) + 9;
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningMachine() is T drawningMachine)
if (elem?.CreateDrawningMachine() is T machine)
{
if (collection.Insert(drawningMachine) == -1)
return false;
try
{
if (collection.Insert(machine) == -1)
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}
/// <summary>
@ -205,7 +207,8 @@ public class StorageCollection<T>
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
private static ICollectionGenericObjects<T>?
CreateCollection(CollectionType collectionType)
{
return collectionType switch
{

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 Tank.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public 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 Tank.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
public 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 Tank.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

@ -86,7 +86,7 @@
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(365, 310);
panelCompanyTools.TabIndex = 9;
panelCompanyTools.Paint += panelCompanyTools_Paint;
//
// buttonAddTank
//
@ -243,7 +243,7 @@
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(342, 40);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//

View File

@ -1,14 +1,19 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tank;
using Tank.CollectionGenericObjects;
using Tank.Drawnings;
using Tank.Drowings;
using Tank.Exceptions;
namespace Tank;
@ -24,6 +29,20 @@ public partial class FormTankCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormTankCollection(ILogger<FormTankCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
///
/// </summary>
@ -38,7 +57,7 @@ public partial class FormTankCollection : Form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
@ -51,15 +70,24 @@ public partial class FormTankCollection : Form
private void SetMachine(DrawningMachine machine)
{
if (_company == null || machine == null) return;
try
{
if (_company == null || machine == null)
{
return;
}
if (_company + machine != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + machine.GetDataForSave());
}
else
}
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -79,14 +107,19 @@ public partial class FormTankCollection : Form
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Удален объект - " + pos);
pictureBox.Image = _company.Show();
}
else
}
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -115,6 +148,8 @@ public partial class FormTankCollection : Form
}
DrawningMachine? tank = null;
int counter = 100;
try
{
while (tank == null)
{
tank = _company.GetRandomObject();
@ -134,12 +169,18 @@ public partial class FormTankCollection : Form
};
form.ShowDialog();
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
@ -155,6 +196,8 @@ public partial class FormTankCollection : Form
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
@ -164,8 +207,15 @@ public partial class FormTankCollection : Form
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
@ -175,12 +225,20 @@ public partial class FormTankCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString() ?? string.Empty);
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
_logger.LogInformation("Коллекция " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Обновление списка в listBoxCollection
@ -214,11 +272,6 @@ public partial class FormTankCollection : Form
}
private void panelCompanyTools_Paint(object sender, PaintEventArgs e)
{
}
/// <summary>
///
/// </summary>
@ -240,13 +293,16 @@ public partial class FormTankCollection : 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);
}
}
}
@ -260,14 +316,19 @@ public partial class FormTankCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storageCollection.LoadData(openFileDialog.FileName);
RefreshListBoxItems();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}",
openFileDialog.FileName);
}
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

@ -1,9 +1,15 @@
namespace Tank
using Tank;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace Tank;
internal static class Program
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
///
/// </summary>
[STAThread]
static void Main()
@ -11,7 +17,23 @@ namespace Tank
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormTankCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider =
services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormTankCollection>());
}
/// <summary>
///
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormTankCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}

View File

@ -8,6 +8,16 @@
<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="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<PackageReference Include="Serilog" Version="4.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +33,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

14
Tank/Tank/nlog.config Normal file
View File

@ -0,0 +1,14 @@
<?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>