12 Commits

Author SHA1 Message Date
60be921810 Final 2022-12-15 06:23:03 +04:00
85f5d7f093 Final 2022-12-12 20:33:30 +04:00
8be22de9a8 fix 2022-12-11 23:17:41 +04:00
4fd89af30e All without change Insert 2022-12-11 23:17:18 +04:00
e527ff439b Initial 2022-12-11 23:00:22 +04:00
3de58e4df9 Fix 2022-12-11 22:58:41 +04:00
3e9def9597 Fix 2022-12-11 22:51:28 +04:00
a20bad8336 Final Commit 2022-12-11 21:44:32 +04:00
0eb06f89e2 Final 2022-11-28 19:31:44 +04:00
ceb8d66616 Logs 2022-11-28 18:00:06 +04:00
a7feb55e23 Exeptions 2022-11-28 17:38:26 +04:00
0c5960afb2 Final 2022-11-24 21:54:29 +04:00
19 changed files with 730 additions and 66 deletions

View File

@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DoubleDeckerBus
{
internal class BusCompareByColor : IComparer<IDrawingObject>
{
public int Compare(IDrawingObject? x, IDrawingObject? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null && y != null)
{
return 1;
}
if (x != null && y == null)
{
return -1;
}
var xBus = x as DrawingObjectBus;
var yBus = y as DrawingObjectBus;
if (xBus == null && yBus == null)
{
return 0;
}
if (xBus == null && yBus != null)
{
return 1;
}
if (xBus != null && yBus == null)
{
return -1;
}
var baseColorCompare = xBus.GetBus.Bus.BodyColor.ToString().CompareTo(yBus.GetBus.Bus.BodyColor.ToString());
if (baseColorCompare != 0)
{
return baseColorCompare;
}
if (xBus.GetBus.Bus is EntityDDB xDDB && yBus.GetBus.Bus is EntityDDB yDDB) {
var extraColorCompare = xDDB.BodyColor.ToString().CompareTo(yDDB.BodyColor.ToString());
if (extraColorCompare != 0)
{
return extraColorCompare;
}
}
return 0;
}
}
}

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DoubleDeckerBus
{
internal class BusCompareByType : IComparer<IDrawingObject>
{
public int Compare(IDrawingObject? x, IDrawingObject? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null && y != null)
{
return 1;
}
if (x != null && y == null)
{
return -1;
}
var xBus = x as DrawingObjectBus;
var yBus = y as DrawingObjectBus;
if (xBus == null && yBus == null)
{
return 0;
}
if (xBus == null && yBus != null)
{
return 1;
}
if (xBus != null && yBus == null)
{
return -1;
}
if (xBus.GetBus.GetType().Name != yBus.GetBus.GetType().Name)
{
if (xBus.GetBus.GetType().Name == "DrawingBus")
{
return -1;
}
return 1;
}
var speedCompare = xBus.GetBus.Bus.Speed.CompareTo(yBus.GetBus.Bus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xBus.GetBus.Bus.Weight.CompareTo(yBus.GetBus.Bus.Weight);
}
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace DoubleDeckerBus
{
[Serializable]
internal class BusNotFoundException : ApplicationException
{
public BusNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public BusNotFoundException() : base() { }
public BusNotFoundException(string message) : base(message) { }
public BusNotFoundException(string message, Exception exception) : base(message, exception) { }
protected BusNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -8,6 +8,30 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="serilog.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="serilog.json">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>serilog.Designer.cs</LastGenOutput>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="5.0.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="FormBus.cs">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
@@ -17,6 +41,11 @@
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Update="serilog.Designer.cs">
<DesignTimeSharedInput>True</DesignTimeSharedInput>
<AutoGen>True</AutoGen>
<DependentUpon>serilog.json</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -8,13 +9,22 @@ namespace DoubleDeckerBus
{
internal class DrawingObjectBus : IDrawingObject
{
private DrawingBus _bus = null;
public DrawingBus? _bus = null;
public DrawingObjectBus(DrawingBus bus)
{
_bus = bus;
}
public DrawingBus? Get_bus()
{
return _bus;
}
public DrawingBus getBus(DrawingBus? _bus) {
return _bus;
}
public float Step => _bus?.Bus?.Step ?? 0;
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
@@ -22,6 +32,11 @@ namespace DoubleDeckerBus
return _bus?.GetCurrentPosition() ?? default;
}
public string? GetInfo()
{
return _bus?.GetDataForSave();
}
public void MoveObject(Direction direction)
{
_bus?.MoveTransport(direction);
@@ -36,5 +51,68 @@ namespace DoubleDeckerBus
{
_bus.DrawTransport(g);
}
public static IDrawingObject Create(string data)
{
return new DrawingObjectBus(data.CreateDrawningCar());
}
public DrawingBus getBus()
{
throw new NotImplementedException();
}
public bool Equals(IDrawingObject? other)
{
if (other == null)
{
return false;
}
var otherBus = other as DrawingObjectBus;
if (otherBus == null)
{
return false;
}
var bus = _bus.Bus;
var otherBusBus = otherBus._bus.Bus;
if (bus.GetType().Name != otherBusBus.GetType().Name)
{
return false;
}
if (bus.Speed != otherBusBus.Speed)
{
return false;
}
if (bus.Weight != otherBusBus.Weight)
{
return false;
}
if (bus.BodyColor != otherBusBus.BodyColor)
{
return false;
}
if (bus is EntityDDB DDB && otherBusBus is EntityDDB otherDDB)
{
if (DDB.Ledder != otherDDB.Ledder) {
return false;
}
if (DDB.SecondStage != otherDDB.SecondStage) {
return false;
}
if (DDB.ExtraColor != otherDDB.ExtraColor)
{
return false;
}
}
return true;
}
public DrawingBus GetBus => _bus;
}
}

View File

@@ -19,5 +19,11 @@ namespace DoubleDeckerBus
Weight = (weight <= 0) ? rnd.Next(50, 70) : weight;
BodyColor = bodyColor;
}
public static EntityBus Creator(string data) {
string[] strs = data.Split(':');
return new EntityBus(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
}
}

View File

@@ -0,0 +1,35 @@
namespace DoubleDeckerBus
{
internal static class ExtentionBus
{
private static readonly char _separatorForObject = ':';
public static DrawingBus CreateDrawningCar(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawingBus(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 6)
{
return new DrawingDDB(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]));
}
return null;
}
public static string GetDataForSave(this DrawingBus drawingBus)
{
var bus = drawingBus.Bus;
var str = $"{bus.Speed}{_separatorForObject}{bus.Weight}{_separatorForObject}{bus.BodyColor.Name}";
if (bus is not EntityDDB sportCar)
{
return str;
}
return $"{str}{_separatorForObject}{sportCar.ExtraColor.Name}{_separatorForObject}{sportCar.SecondStage}{_separatorForObject}{sportCar.Ledder}";
}
}
}

View File

@@ -143,7 +143,7 @@ namespace DoubleDeckerBus
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
{
EventAddBus?.Invoke(_bus);
Close();
}

View File

@@ -39,19 +39,30 @@
this.buttonDown = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.buttonShowStorage = new System.Windows.Forms.Button();
this.buttonDeleteBus = new System.Windows.Forms.Button();
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.buttonAddBus = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.FileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.button1 = new System.Windows.Forms.Button();
this.buttonShowStorage = new System.Windows.Forms.Button();
this.ButtonSortByColor = new System.Windows.Forms.Button();
this.ButtonSortByType = new System.Windows.Forms.Button();
this.groupBoxSettings.SuspendLayout();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// groupBoxSettings
//
this.groupBoxSettings.Controls.Add(this.ButtonSortByColor);
this.groupBoxSettings.Controls.Add(this.ButtonSortByType);
this.groupBoxSettings.Controls.Add(this.groupBox1);
this.groupBoxSettings.Controls.Add(this.buttonRight);
this.groupBoxSettings.Controls.Add(this.buttonDown);
@@ -63,9 +74,9 @@
this.groupBoxSettings.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxSettings.Controls.Add(this.buttonAddBus);
this.groupBoxSettings.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxSettings.Location = new System.Drawing.Point(645, 0);
this.groupBoxSettings.Location = new System.Drawing.Point(645, 24);
this.groupBoxSettings.Name = "groupBoxSettings";
this.groupBoxSettings.Size = new System.Drawing.Size(200, 643);
this.groupBoxSettings.Size = new System.Drawing.Size(200, 710);
this.groupBoxSettings.TabIndex = 0;
this.groupBoxSettings.TabStop = false;
this.groupBoxSettings.Text = "Инструменты";
@@ -134,7 +145,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::DoubleDeckerBus.Properties.Resources.RightArrow;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(109, 591);
this.buttonRight.Location = new System.Drawing.Point(109, 658);
this.buttonRight.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(26, 22);
@@ -148,7 +159,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::DoubleDeckerBus.Properties.Resources.DownArrow;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(86, 610);
this.buttonDown.Location = new System.Drawing.Point(86, 677);
this.buttonDown.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(26, 22);
@@ -162,7 +173,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::DoubleDeckerBus.Properties.Resources.LeftArrow;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(63, 591);
this.buttonLeft.Location = new System.Drawing.Point(63, 658);
this.buttonLeft.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(26, 22);
@@ -176,7 +187,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::DoubleDeckerBus.Properties.Resources.UpArrow;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(85, 572);
this.buttonUp.Location = new System.Drawing.Point(85, 639);
this.buttonUp.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(26, 22);
@@ -185,29 +196,9 @@
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// button1
//
this.button1.Location = new System.Drawing.Point(6, 521);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(182, 35);
this.button1.TabIndex = 5;
this.button1.Text = "Посмотреть карту";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.ButtonShowOnMap_Click);
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(6, 480);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(182, 35);
this.buttonShowStorage.TabIndex = 4;
this.buttonShowStorage.Text = "Посмотреть хранилище";
this.buttonShowStorage.UseVisualStyleBackColor = true;
this.buttonShowStorage.Click += new System.EventHandler(this.ButtonShowStorage_Click);
//
// buttonDeleteBus
//
this.buttonDeleteBus.Location = new System.Drawing.Point(6, 438);
this.buttonDeleteBus.Location = new System.Drawing.Point(6, 522);
this.buttonDeleteBus.Name = "buttonDeleteBus";
this.buttonDeleteBus.Size = new System.Drawing.Size(188, 36);
this.buttonDeleteBus.TabIndex = 3;
@@ -217,7 +208,7 @@
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(6, 409);
this.maskedTextBoxPosition.Location = new System.Drawing.Point(6, 493);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(188, 23);
@@ -225,7 +216,7 @@
//
// buttonAddBus
//
this.buttonAddBus.Location = new System.Drawing.Point(6, 367);
this.buttonAddBus.Location = new System.Drawing.Point(6, 451);
this.buttonAddBus.Name = "buttonAddBus";
this.buttonAddBus.Size = new System.Drawing.Size(188, 36);
this.buttonAddBus.TabIndex = 1;
@@ -236,19 +227,105 @@
// pictureBox
//
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 0);
this.pictureBox.Location = new System.Drawing.Point(0, 24);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(645, 643);
this.pictureBox.Size = new System.Drawing.Size(645, 710);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// menuStrip1
//
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.FileToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Padding = new System.Windows.Forms.Padding(5, 2, 0, 2);
this.menuStrip1.Size = new System.Drawing.Size(845, 24);
this.menuStrip1.TabIndex = 2;
this.menuStrip1.Text = "menuStrip1";
//
// FileToolStripMenuItem
//
this.FileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.FileToolStripMenuItem.Name = "FileToolStripMenuItem";
this.FileToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// button1
//
this.button1.Location = new System.Drawing.Point(6, 605);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(182, 35);
this.button1.TabIndex = 5;
this.button1.Text = "Посмотреть карту";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.ButtonShowOnMap_Click);
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(6, 564);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(182, 35);
this.buttonShowStorage.TabIndex = 4;
this.buttonShowStorage.Text = "Посмотреть хранилище";
this.buttonShowStorage.UseVisualStyleBackColor = true;
this.buttonShowStorage.Click += new System.EventHandler(this.ButtonShowStorage_Click);
//
// ButtonSortByColor
//
this.ButtonSortByColor.Location = new System.Drawing.Point(12, 402);
this.ButtonSortByColor.Name = "ButtonSortByColor";
this.ButtonSortByColor.Size = new System.Drawing.Size(182, 35);
this.ButtonSortByColor.TabIndex = 13;
this.ButtonSortByColor.Text = "Сортировать по цвету";
this.ButtonSortByColor.UseVisualStyleBackColor = true;
this.ButtonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// ButtonSortByType
//
this.ButtonSortByType.Location = new System.Drawing.Point(12, 361);
this.ButtonSortByType.Name = "ButtonSortByType";
this.ButtonSortByType.Size = new System.Drawing.Size(182, 35);
this.ButtonSortByType.TabIndex = 12;
this.ButtonSortByType.Text = "Сортировать по типу";
this.ButtonSortByType.UseVisualStyleBackColor = true;
this.ButtonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// FormMapWithSetBuses
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(845, 643);
this.ClientSize = new System.Drawing.Size(845, 734);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxSettings);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormMapWithSetBuses";
this.Text = "Карты с набором объектов";
this.groupBoxSettings.ResumeLayout(false);
@@ -256,7 +333,10 @@
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@@ -267,8 +347,6 @@
private Button buttonAddBus;
private Button buttonDeleteBus;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonShowStorage;
private Button button1;
private Button buttonRight;
private Button buttonDown;
private Button buttonLeft;
@@ -279,5 +357,15 @@
private Button ButtonDeleteMap;
private Button ButtonAddMap;
private ListBox listBoxMaps;
private MenuStrip menuStrip1;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button ButtonSortByColor;
private Button ButtonSortByType;
private Button button1;
private Button buttonShowStorage;
}
}

View File

@@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -21,9 +22,12 @@ namespace DoubleDeckerBus
private readonly MapsCollection _mapsCollection;
public FormMapWithSetBuses()
private readonly ILogger _logger;
public FormMapWithSetBuses(ILogger<FormMapWithSetBuses> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var item in _mapsDict) {
@@ -54,27 +58,32 @@ namespace DoubleDeckerBus
private void ButtonAddBus_Click(object sender, EventArgs e)
{
var formBusConfig = new FormBusConfig();
// TODO Call method AddEvent from fromBusConfig
formBusConfig.AddEvent(AddBus);
formBusConfig.Show();
}
private void AddBus(DrawingBus bus)
{
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
DrawingObjectBus boat = new(bus);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat >= 0)
try
{
DrawingObjectBus _bus = new(bus);
_ = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + _bus;
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Объект добавлен");
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show($"Не удалось добавить объект {ex.Message}");
_logger.LogInformation($"Объект не добаавлен {ex.Message}");
}
catch (Exception ex) {
MessageBox.Show($"Не удалось добавить объект {ex.Message}");
_logger.LogInformation($"Объект не добаавлен {ex.Message}");
}
}
@@ -89,15 +98,31 @@ namespace DoubleDeckerBus
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation($"Объект не удален");
}
}
else
catch (BusNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show($"Ошибка удаления: {ex.Message}");
_logger.LogWarning("Автобус не найден");
}
catch (Exception ex)
{
MessageBox.Show($"Неизветсная шибка: {ex.Message}");
_logger.LogWarning("Неизвестная ошибка при удалении");
}
}
private void ButtonShowStorage_Click(object sender, EventArgs e)
@@ -107,6 +132,7 @@ namespace DoubleDeckerBus
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Отображение хранилища");
}
private void ButtonShowOnMap_Click(object sender, EventArgs e)
@@ -116,6 +142,7 @@ namespace DoubleDeckerBus
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
_logger.LogInformation($"Отображение карты");
}
private void ButtonMove_Click(object sender, EventArgs e)
@@ -143,6 +170,7 @@ namespace DoubleDeckerBus
break;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
_logger.LogInformation($"Передвижение {name}");
}
private void ButtonAddMap_Click(object sender, EventArgs e)
@@ -150,35 +178,95 @@ namespace DoubleDeckerBus
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не все данные заполнены при добавлени карты");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Нет такой карты {comboBoxSelectorMap.Text}");
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Выбраная карта изменилась {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
private void ButtonDeleteMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
_logger.LogWarning("Удаление карты не произошло. Не выбрана карта");
return;
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
ReloadMaps();
}
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение {openFileDialog.FileName} прошло успешно");
}
catch (Exception ex) {
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Сохранение {openFileDialog.FileName} прошло не успешно");
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try {
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузка из файла {openFileDialog.FileName} прошла успешна");
ReloadMaps();
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка при загрузке: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} прошла не успешно");
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1) {
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? String.Empty].Sort(new BusCompareByType());
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? String.Empty].Sort(new BusCompareByColor());
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
}
}

View File

@@ -57,4 +57,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>152, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>319, 17</value>
</metadata>
</root>

View File

@@ -6,8 +6,9 @@ using System.Threading.Tasks;
namespace DoubleDeckerBus
{
internal interface IDrawingObject
internal interface IDrawingObject : IEquatable<IDrawingObject>
{
public DrawingBus getBus();
public float Step { get; }
void SetObject(int x, int y, int width, int height);
@@ -18,5 +19,6 @@ namespace DoubleDeckerBus
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
string GetInfo();
}
}

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace DoubleDeckerBus
{
internal class MapWithSetBusesGeneric<T, U>
where T : class, IDrawingObject
where T : class, IDrawingObject, IEquatable<T>
where U : AbstractMap
{
@@ -29,7 +29,7 @@ namespace DoubleDeckerBus
}
public static int operator +(MapWithSetBusesGeneric<T, U> map, T bus)
{
{
return map._setBuses.Insert(bus);
}
@@ -140,5 +140,27 @@ namespace DoubleDeckerBus
if (currentHeight > height) return;
}
}
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var bus in _setBuses.GetBuses())
{
data += $"{bus.GetInfo()}{separatorData}";
}
return data;
}
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setBuses.Insert(DrawingObjectBus.Create(rec) as T);
}
}
public void Sort(IComparer<T> comparer) {
_setBuses.SortSet(comparer);
}
}
}

View File

@@ -1,21 +1,26 @@
using DoubleDeckerBus;
using System.Text;
namespace DoubleDeckerBus
{
internal class MapsCollection
{
readonly Dictionary<string, MapWithSetBusesGeneric<DrawingObjectBus, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetBusesGeneric<IDrawingObject, AbstractMap>> _mapStorages;
public List<string> Keys => _mapStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private readonly char separatorDict = '|';
private readonly char separatorData = ';';
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetBusesGeneric<DrawingObjectBus, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetBusesGeneric<IDrawingObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -23,7 +28,7 @@ namespace DoubleDeckerBus
public void AddMap(string name, AbstractMap map)
{
if (Keys.Contains(name)) return;
_mapStorages.Add(name, new MapWithSetBusesGeneric<DrawingObjectBus, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.Add(name, new MapWithSetBusesGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
public void DelMap(string name)
@@ -31,7 +36,7 @@ namespace DoubleDeckerBus
_mapStorages.Remove(name);
}
public MapWithSetBusesGeneric<DrawingObjectBus, AbstractMap> this[string ind]
public MapWithSetBusesGeneric<IDrawingObject, AbstractMap> this[string ind]
{
get
{
@@ -39,5 +44,64 @@ namespace DoubleDeckerBus
return result;
}
}
private static void WriteToFile(string text, FileStream stream)
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length);
}
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new(filename))
{
sw.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
string line;
using (StreamReader sw = new(filename))
{
line = sw.ReadLine();
if (line == null || !line.Contains("MapsCollection"))
{
throw new FileFormatException("Формат данных в файле не совпадает");
}
_mapStorages.Clear();
line = sw.ReadLine();
while (line != null)
{
var elem = line.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "WaterMap":
map = new WaterMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetBusesGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
line = sw.ReadLine();
}
}
}
}
}
}

View File

@@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Logging;
namespace DoubleDeckerBus
{
internal static class Program
@@ -11,7 +17,27 @@ namespace DoubleDeckerBus
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetBuses());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetBuses>());
}
}
private static void ConfigureServices(ServiceCollection services) {
services.AddSingleton<FormMapWithSetBuses>().AddLogging(option =>
{
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: "serilog.json").Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace DoubleDeckerBus
{
internal class SetBusesGeneric<T>
where T : class
where T : class, IEquatable<T>
{
private readonly List<T> _places;
@@ -29,7 +29,16 @@ namespace DoubleDeckerBus
public int Insert(T bus, int position)
{
if (position < 0 || position >= _maxCount || BusyPlaces == _maxCount) return -1;
if (_places.Contains(bus))
{
throw new ArgumentException("The same bus exist");
}
if (position < 0 || position >= _maxCount)
{
throw new BusNotFoundException("Место указано неверно");
}
BusyPlaces++;
_places.Insert(position, bus);
@@ -38,7 +47,10 @@ namespace DoubleDeckerBus
public T Remove(int position)
{
if (position < 0 || position >= _maxCount) return null;
if (position < 0 || position >= _maxCount) {
throw new BusNotFoundException(position);
}
T savedBus = _places[position];
_places.RemoveAt(position);
return savedBus;
@@ -46,7 +58,7 @@ namespace DoubleDeckerBus
public T this[int position] {
get {
if (position < 0 || position >= _maxCount) return null;
if (position < 0 || position >= _maxCount) return default(T);
return _places[position];
}
set {
@@ -68,5 +80,12 @@ namespace DoubleDeckerBus
}
}
}
public void SortSet(IComparer<T> comparer) {
if (comparer == null) {
return;
}
_places.Sort(comparer);
}
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace DoubleDeckerBus
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -0,0 +1,26 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DoubleDeckerBus {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.3.0.0")]
internal sealed partial class serilog : global::System.Configuration.ApplicationSettingsBase {
private static serilog defaultInstance = ((serilog)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new serilog())));
public static serilog Default {
get {
return defaultInstance;
}
}
}
}

View File

@@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "DoubleDeckerBus"
}
}
}