доделанная лаба 7

This commit is contained in:
tyxz0 2024-06-05 01:51:55 +04:00
parent 0b7ebcdcc0
commit 038b8261a5
12 changed files with 234 additions and 73 deletions

View File

@ -42,7 +42,7 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Вычисление максимального кол-ва элементов, который можно разместить в окне /// Вычисление максимального кол-ва элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => (_pictureWidth / (_placeSizeWidth + 75)) * (_pictureHeight / _placeSizeHeight);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -99,8 +99,16 @@ public abstract class AbstractCompany
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{ {
DrawingBus? obj = _collection?.Get(i); try
obj?.DrawTrasnport(graphics); {
DrawingBus? obj = _collection?.Get(i);
obj?.DrawTrasnport(graphics);
}
catch(Exception)
{
continue;
}
} }
return bitmap; return bitmap;

View File

@ -54,8 +54,16 @@ public class BusStation : AbstractCompany
for (int i = 0, coordinate_index = 0; i < _collection.Count; i++, coordinate_index += 2) for (int i = 0, coordinate_index = 0; i < _collection.Count; i++, coordinate_index += 2)
{ {
_collection.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); try
_collection.Get(i)?.SetPosition(_arrayOfCoordinates[coordinate_index], _arrayOfCoordinates[coordinate_index + 1]); {
_collection.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i)?.SetPosition(_arrayOfCoordinates[coordinate_index], _arrayOfCoordinates[coordinate_index + 1]);
}
catch (Exception)
{
break;
}
} }
} }

View File

@ -1,4 +1,5 @@
using System; using DoubleDeckerBus.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -38,7 +39,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return null; throw new PositionOutOfCollectionException(position);
} }
return _collection[position]; return _collection[position];
} }
@ -47,7 +48,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{ {
if (Count >= _maxCount) if (Count >= _maxCount)
{ {
return -1; throw new CollectionOverflowException(Count);
} }
_collection.Add(obj); _collection.Add(obj);
return _collection.IndexOf(obj); return _collection.IndexOf(obj);
@ -55,9 +56,14 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (Count >= _maxCount || position < 0 || position >= _maxCount) if (position < 0 || position >= _maxCount)
{ {
return -1; throw new PositionOutOfCollectionException(position);
}
if (Count >= MaxCount)
{
throw new CollectionOverflowException(Count);
} }
if (position > Count && position < _maxCount) if (position > Count && position < _maxCount)
@ -65,36 +71,16 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return Insert(obj); return Insert(obj);
} }
int copy_of_position = position - 1; _collection.Insert(position, obj);
while (position < Count) return position;
{
if (_collection[position] == null)
{
_collection.Insert(position, obj);
return position;
}
position++;
}
while (copy_of_position > 0)
{
if (_collection[copy_of_position] == null)
{
_collection.Insert(copy_of_position, obj);
return copy_of_position;
}
copy_of_position--;
}
return -1;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return null; throw new PositionOutOfCollectionException(position);
} }
T? removed_object = Get(position); T? removed_object = Get(position);

View File

@ -1,4 +1,5 @@
using System; using DoubleDeckerBus.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -52,25 +53,35 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return null; throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
} }
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
return Insert(obj, 0); try
{
return Insert(obj, 0);
}
catch(CollectionOverflowException ex)
{
throw new CollectionOverflowException(ex.Message);
}
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return -1; throw new PositionOutOfCollectionException(position);
} }
int copy_of_position = position - 1; int copy_of_position = position - 1;
while (position < Count) while (position < Count)
@ -92,7 +103,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
copy_of_position--; copy_of_position--;
} }
return -1; throw new CollectionOverflowException(Count);
} }
@ -100,7 +111,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return null; throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
} }
T? removed_object = _collection[position]; T? removed_object = _collection[position];

View File

@ -1,4 +1,5 @@
using DoubleDeckerBus.Drawnings; using DoubleDeckerBus.Drawnings;
using DoubleDeckerBus.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -79,11 +80,11 @@ public 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 ArgumentException("There are no collections to save");
} }
if (File.Exists(filename)) if (File.Exists(filename))
@ -127,26 +128,22 @@ public class StorageCollection<T>
sw.WriteLine(sb.ToString()); sw.WriteLine(sb.ToString());
} }
} }
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("The file does not exist");
} }
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
{ {
string? bufferLine = sr.ReadLine(); string? bufferLine = sr.ReadLine();
if (bufferLine != _collectionKey) if (bufferLine != _collectionKey)
{ {
return false; throw new ArgumentException("Invalid data in the file");
} }
_storages.Clear(); _storages.Clear();
@ -165,7 +162,7 @@ public class StorageCollection<T>
if (collection == null) if (collection == null)
{ {
return false; throw new ArgumentNullException("Failed to create a collection");
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
@ -176,17 +173,20 @@ public class StorageCollection<T>
{ {
if (elem?.CreateDrawningCar() is T car) if (elem?.CreateDrawningCar() is T car)
{ {
if (collection.Insert(car) == -1) try
{ {
return false; collection.Insert(car);
} }
catch(CollectionOverflowException ex)
{
throw new CollectionOverflowException("The collection is overflowing", ex);
}
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
return true; }
}
} }
/// <summary> /// <summary>

View File

@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="7.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -23,4 +34,12 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ProjectExtensions><VisualStudio><UserProperties /></VisualStudio></ProjectExtensions>
</Project> </Project>

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 DoubleDeckerBus.Exceptions;
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("The allowed amount in the collection has been exceeded: " + 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 DoubleDeckerBus.Exceptions;
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("The object was not found by position " + 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 DoubleDeckerBus.Exceptions;
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Going beyond the boundaries of the collection. Position: " + 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,6 @@
using DoubleDeckerBus.CollectionGenericObjects; using DoubleDeckerBus.CollectionGenericObjects;
using DoubleDeckerBus.Drawnings; using DoubleDeckerBus.Drawnings;
using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -18,13 +19,16 @@ public partial class FormBusCollection : Form
private readonly StorageCollection<DrawingBus> _storageCollection; private readonly StorageCollection<DrawingBus> _storageCollection;
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormBusCollection() public FormBusCollection(ILogger<FormBusCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
private void comboBoxSelectCompany_SelectedIndexChanged(object sender, EventArgs e) private void comboBoxSelectCompany_SelectedIndexChanged(object sender, EventArgs e)
@ -46,14 +50,20 @@ public partial class FormBusCollection : Form
return; return;
} }
if ((_company + bus) != -1) try
{ {
MessageBox.Show("Object added"); if ((_company + bus) != -1)
pictureBox.Image = _company.Show(); {
MessageBox.Show("Object added");
pictureBox.Image = _company.Show();
_logger.LogInformation("Object added: {obj}", bus.GetDataForSave());
}
} }
else catch (Exception ex)
{ {
MessageBox.Show("Failed to add object"); MessageBox.Show(ex.Message);
_logger.LogError("Failed to add object", ex.Message);
} }
} }
@ -72,16 +82,19 @@ public partial class FormBusCollection : Form
} }
int pos = Convert.ToInt32(maskedTextBox.Text); int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
try
{ {
DrawingBus? removedObj = _company - pos;
MessageBox.Show("Object removed"); MessageBox.Show("Object removed");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Object removed {obj}", removedObj?.GetDataForSave());
} }
else catch(Exception ex)
{ {
MessageBox.Show("Failed to remove object"); MessageBox.Show(ex.Message);
_logger.LogError("Failed to remove object", ex.Message);
} }
} }
private void ButtonGoToCheck_Click(object sender, EventArgs e) private void ButtonGoToCheck_Click(object sender, EventArgs e)
@ -130,6 +143,7 @@ public partial class FormBusCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonArray.Checked && !radioButtonList.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonArray.Checked && !radioButtonList.Checked))
{ {
MessageBox.Show("Not all data is filled in", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Not all data is filled in", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Failed to add collection: not all data is filled in");
return; return;
} }
@ -144,6 +158,7 @@ public partial class FormBusCollection : Form
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Added a collection of type {type} with the name {name}", collectionType, textBoxCollectionName.Text);
RefreshListBoxItems(); RefreshListBoxItems();
} }
@ -165,6 +180,7 @@ public partial class FormBusCollection : Form
if (listBoxCollectionItems.SelectedIndex < 0) if (listBoxCollectionItems.SelectedIndex < 0)
{ {
MessageBox.Show("No collection selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("No collection selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Failed to remove collection: no collection selected");
return; return;
} }
@ -175,6 +191,7 @@ public partial class FormBusCollection : Form
if (result == DialogResult.Yes) if (result == DialogResult.Yes)
{ {
_storageCollection.DelCollection(listBoxCollectionItems.Text); _storageCollection.DelCollection(listBoxCollectionItems.Text);
_logger.LogInformation("Removed a collection {name}: ", listBoxCollectionItems.SelectedItem?.ToString());
RefreshListBoxItems(); RefreshListBoxItems();
} }
else else
@ -211,31 +228,37 @@ public partial class FormBusCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Save succeeded", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Save succeeded", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Saving to the file: {filename}", saveFileDialog.FileName);
} }
else catch(Exception ex)
{ {
MessageBox.Show("Unable to save", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Unable to save", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Error: {Message}", ex.Message);
} }
} }
} }
private void LoadToolStripMenuItem_Click(object sender, EventArgs e) private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Load succeeded", "Resilt", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Load succeeded", "Resilt", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Loading from the file: {filename}", openFileDialog.FileName);
RefreshListBoxItems(); RefreshListBoxItems();
} }
else catch(Exception ex)
{ {
MessageBox.Show("Unable to load", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Unable to load", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Error: {Message}", ex.Message);
} }
} }
} }

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace DoubleDeckerBus namespace DoubleDeckerBus
{ {
internal static class Program internal static class Program
@ -11,7 +16,23 @@ namespace DoubleDeckerBus
// 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 FormBusCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider servicesProvider = services.BuildServiceProvider();
Application.Run(servicesProvider.GetRequiredService<FormBusCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBusCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(new ConfigurationBuilder().
SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("serilog.json").Build()).CreateLogger());
});
} }
} }
} }

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "buslog-${shortdate}.log",
"Args": { "path": "C:\\Users\\Админ\\Desktop" }
}
],
"Properties": {
"Applicatoin": "Sample"
}
}
}