This commit is contained in:
kirkorovka 2024-06-09 02:07:07 +04:00
parent 6f06ed0ff6
commit c2e139d3e3
22 changed files with 323 additions and 138 deletions

View File

@ -19,7 +19,7 @@ public abstract class AbstractCompany
protected ICollectionGenericObjects<DrawingBase>? _collection = null; protected ICollectionGenericObjects<DrawingBase>? _collection = null;
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight) - 1;
public AbstractCompany(int picWidth, int picHeigth, ICollectionGenericObjects<DrawingBase> collection) public AbstractCompany(int picWidth, int picHeigth, ICollectionGenericObjects<DrawingBase> collection)
{ {

View File

@ -1,4 +1,5 @@
using System; using Project_SelfPropelledArtilleryUnit.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -35,30 +36,46 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= _collection.Count || _collection == null || _collection.Count == 0) return null; if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
if (Count == _maxCount) return -1; if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
_collection.Add(obj); _collection.Add(obj);
return _collection.Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (Count == _maxCount || position < 0 || position > Count) return -1; if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
if (position >= Count || position < 0)
{
throw new CollectionOverflowException(Count);
}
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (_collection == null || position < 0 || position >= _collection.Count) return null; if (position >= Count || position < 0)
T? obj = _collection[position]; {
_collection[position] = null; throw new PositionOutOfCollectionException(position);
}
T obj = _collection[position];
_collection.RemoveAt(position);
return obj; return obj;
} }

View File

@ -1,4 +1,5 @@
using Project_SelfPropelledArtilleryUnit.Drawings; using Project_SelfPropelledArtilleryUnit.Drawings;
using Project_SelfPropelledArtilleryUnit.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -7,7 +8,7 @@ using System.Threading.Tasks;
namespace Project_SelfPropelledArtilleryUnit.CollectionGenericObjects; namespace Project_SelfPropelledArtilleryUnit.CollectionGenericObjects;
public class MassiveGenericObjects <T> : ICollectionGenericObjects<T> public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
{ {
private T?[] _collection; private T?[] _collection;
@ -43,77 +44,79 @@ public class MassiveGenericObjects <T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= Count)
if (position >= _collection.Length || position < 0)
{ {
return null; throw new PositionOutOfCollectionException(position);
} }
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
int index = 0; throw new CollectionOverflowException(Count);
while (index < _collection.Length)
{
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
index++;
}
return -1;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position < 0 || position >= Count)
if (position >= _collection.Length || position < 0)
return -1;
if (_collection[position] != null)
{ {
throw new PositionOutOfCollectionException(position);
}
int nullIndex = -1; if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
else
{
for (int i = position + 1; i < Count; i++) for (int i = position + 1; i < Count; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
{ {
nullIndex = i; _collection[i] = obj;
break; return i;
} }
} }
if (nullIndex < 0) for (int i = 0; i < position; i++)
{ {
return -1; if (_collection[i] == null)
}
int j = nullIndex - 1;
while (j >= position)
{ {
_collection[j + 1] = _collection[j]; _collection[i] = obj;
j--; return i;
}
} }
} }
_collection[position] = obj; throw new CollectionOverflowException(Count);
return position;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position >= _collection.Length || position < 0) if (position >= Count || position < 0)
{ {
return null; throw new PositionOutOfCollectionException(position);
}
T? obj = _collection[position];
if (obj == null)
{
throw new ObjectNotFoundException(position);
} }
T temp = _collection[position];
_collection[position] = null; _collection[position] = null;
return temp; return obj;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()

View File

@ -1,4 +1,5 @@
using Project_SelfPropelledArtilleryUnit.Drawings; using Project_SelfPropelledArtilleryUnit.Drawings;
using Project_SelfPropelledArtilleryUnit.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -55,11 +56,11 @@ internal class StorageCollection<T>
} }
} }
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
@ -97,25 +98,25 @@ internal class StorageCollection<T>
} }
} }
} }
return true;
} }
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не существует");
} }
using (StreamReader reader = new(filename)) using (StreamReader reader = new(filename))
{ {
string line = reader.ReadLine(); string line = reader.ReadLine();
if (line == null || line.Length == 0) if (line == null || line.Length == 0)
{ {
return false; throw new IOException("В файле нет данных");
} }
if (!line.Equals(_collectionKey)) if (!line.Equals(_collectionKey))
{ {
return false; throw new IOException("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
while ((line = reader.ReadLine()) != null) while ((line = reader.ReadLine()) != null)
@ -129,7 +130,7 @@ internal class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new IOException("В файле нет данных");
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
@ -139,14 +140,23 @@ internal class StorageCollection<T>
{ {
if (collection.Insert(truck) == -1) if (collection.Insert(truck) == -1)
{ {
return false; try
{
if (collection.Insert(truck) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
} }
return true;
} }

View File

@ -29,7 +29,7 @@ namespace Project_SelfPropelledArtilleryUnit.Drawings
public DrawingBase(int speed, double weight, Color bodyColor) : this() public DrawingBase(int speed, double weight, Color bodyColor) : this()
{ {
BaseSAU =new BaseSAU(speed, weight, bodyColor); BaseSAU = new BaseSAU(speed, weight, bodyColor);
} }
public DrawingBase() public DrawingBase()
@ -40,7 +40,7 @@ namespace Project_SelfPropelledArtilleryUnit.Drawings
_startPosY = null; _startPosY = null;
} }
public DrawingBase(int width,int height) : this() public DrawingBase(int width, int height) : this()
{ {
_drawingSAUWidth = width; _drawingSAUWidth = width;
_drawingSAUHeight = height; _drawingSAUHeight = height;

View File

@ -14,7 +14,7 @@ public class DrawingSAU : DrawingBase
public DrawingSAU(int speed, double weight, Color bodyColor, Color additionalColor, bool tracks, bool guns) : base(150, 100) public DrawingSAU(int speed, double weight, Color bodyColor, Color additionalColor, bool tracks, bool guns) : base(150, 100)
{ {
BaseSAU = new EntitySAU( speed, weight, bodyColor, additionalColor, tracks, guns); BaseSAU = new EntitySAU(speed, weight, bodyColor, additionalColor, tracks, guns);
} }
public DrawingSAU(BaseSAU? baseSAU) public DrawingSAU(BaseSAU? baseSAU)
@ -27,7 +27,7 @@ public class DrawingSAU : DrawingBase
public override void DrawSAU(Graphics g) public override void DrawSAU(Graphics g)
{ {
if (BaseSAU==null || BaseSAU is not EntitySAU SAU || !_startPosX.HasValue || !_startPosY.HasValue) if (BaseSAU == null || BaseSAU is not EntitySAU SAU || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return; return;
} }

View File

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace Project_SelfPropelledArtilleryUnit.Entity; namespace Project_SelfPropelledArtilleryUnit.Entity;
public class EntitySAU: BaseSAU public class EntitySAU : BaseSAU
{ {

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 Project_SelfPropelledArtilleryUnit.Exceptions;
[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,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Project_SelfPropelledArtilleryUnit.Exceptions;
[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,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Project_SelfPropelledArtilleryUnit.Exceptions;
[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,9 @@
using Project_SelfPropelledArtilleryUnit.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.Logging;
using NLog;
using Project_SelfPropelledArtilleryUnit.CollectionGenericObjects;
using Project_SelfPropelledArtilleryUnit.Drawings; using Project_SelfPropelledArtilleryUnit.Drawings;
using Project_SelfPropelledArtilleryUnit.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -10,6 +14,7 @@ using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace Project_SelfPropelledArtilleryUnit; namespace Project_SelfPropelledArtilleryUnit;
@ -17,10 +22,13 @@ public partial class FormSAUCollection : Form
{ {
private readonly StorageCollection<DrawingBase> _storageCollection; private readonly StorageCollection<DrawingBase> _storageCollection;
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
public FormSAUCollection() private readonly ILogger _logger;
public FormSAUCollection(ILogger<FormSAUCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма создалась");
} }
@ -40,7 +48,9 @@ public partial class FormSAUCollection : Form
form.AddEvent(SetSAU); form.AddEvent(SetSAU);
} }
private void SetSAU(DrawingBase sau) private void SetSAU(DrawingBase? sau)
{
try
{ {
if (_company == null || sau == null) if (_company == null || sau == null)
{ {
@ -51,10 +61,14 @@ public partial class FormSAUCollection : Form
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + sau.GetDataForSave());
} }
else }
catch (ObjectNotFoundException ex) { }
catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -71,14 +85,19 @@ public partial class FormSAUCollection : Form
} }
int pos = Convert.ToInt32(maskedTextBox.Text); int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
if (_company - pos != null) if (_company - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
} }
else }
catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -211,13 +230,16 @@ public partial class FormSAUCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); 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);
} }
} }
} }
@ -226,15 +248,18 @@ public partial class FormSAUCollection : Form
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошла успешно", "Реузльтат", MessageBoxButtons.OK, MessageBoxIcon.Information); _storageCollection.LoadData(openFileDialog.FileName);
UpdateListBoxItems(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_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);
} }
} }
UpdateListBoxItems();
} }
} }

View File

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

View File

@ -8,6 +8,36 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Content Include="bin\Debug\net8.0-windows\Logs\log20240520.txt" />
<Content Include="bin\Debug\net8.0-windows\Project_SelfPropelledArtilleryUnit.deps.json" />
<Content Include="bin\Debug\net8.0-windows\Project_SelfPropelledArtilleryUnit.runtimeconfig.json" />
</ItemGroup>
<ItemGroup>
<None Include="bin\Debug\net8.0-windows\carlog-2024-05-19.log" />
<None Include="bin\Debug\net8.0-windows\carlog-2024-05-20.log" />
<None Include="bin\Debug\net8.0-windows\Microsoft.Extensions.Configuration.Abstractions.dll" />
<None Include="bin\Debug\net8.0-windows\Microsoft.Extensions.DependencyInjection.Abstractions.dll" />
<None Include="bin\Debug\net8.0-windows\Microsoft.Extensions.DependencyInjection.dll" />
<None Include="bin\Debug\net8.0-windows\Microsoft.Extensions.Logging.Abstractions.dll" />
<None Include="bin\Debug\net8.0-windows\Microsoft.Extensions.Logging.dll" />
<None Include="bin\Debug\net8.0-windows\Microsoft.Extensions.Options.dll" />
<None Include="bin\Debug\net8.0-windows\Microsoft.Extensions.Primitives.dll" />
<None Include="bin\Debug\net8.0-windows\NLog.dll" />
<None Include="bin\Debug\net8.0-windows\NLog.Extensions.Logging.dll" />
<None Include="bin\Debug\net8.0-windows\Project_SelfPropelledArtilleryUnit.dll" />
<None Include="bin\Debug\net8.0-windows\Project_SelfPropelledArtilleryUnit.exe" />
<None Include="bin\Debug\net8.0-windows\Project_SelfPropelledArtilleryUnit.pdb" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.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.11" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

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>