MongoDBImplement / Add Data transfer

This commit is contained in:
parent 63995f51c2
commit ab513e4064
8 changed files with 716 additions and 465 deletions

View File

@ -0,0 +1,234 @@
using MongoDB.Bson;
using MongoDB.Driver;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideMongoDBImplement
{
/// <summary>
/// Класс для переноса данных между БД
/// </summary>
public class DataTransfer
{
/// <summary>
/// Параметры подключения к базе данных PostgreSQL
/// </summary>
private readonly string _pgsqlDBConnectionString = "Host=192.168.0.108;Port=5432;Database=RouteGuide;Username=postgres;Password=2004";
/// <summary>
/// Параметры подключения к базе данных MongoDB
/// </summary>
private readonly string _mongoDBConnectionString = "mongodb://localhost:27017";
/// <summary>
/// Название базы данных
/// </summary>
private readonly string _databaseName = "RouteGuideDatabase";
/// <summary>
/// Клиент MongoDB
/// </summary>
public readonly MongoClient _client;
/// <summary>
/// База данных MongoDB
/// </summary>
private readonly IMongoDatabase _database;
/// <summary>
/// Коллекция "Водители"
/// </summary>
private IMongoCollection<BsonDocument> Drivers => _database.GetCollection<BsonDocument>("Drivers");
/// <summary>
/// Коллекция "Транспорт"
/// </summary>
private IMongoCollection<BsonDocument> Transport => _database.GetCollection<BsonDocument>("Transport");
/// <summary>
/// Коллекция "Маршруты"
/// </summary>
private IMongoCollection<BsonDocument> Routes => _database.GetCollection<BsonDocument>("Routes");
/// <summary>
/// Коллекция "Остановки"
/// </summary>
private IMongoCollection<BsonDocument> Stops => _database.GetCollection<BsonDocument>("Stops");
/// <summary>
/// Связь для сущностей "Маршруты" и "Остановки"
/// </summary>
private IMongoCollection<BsonDocument> RouteStops => _database.GetCollection<BsonDocument>("RouteStops");
/// <summary>
/// Коллекция "Расписания"
/// </summary>
private IMongoCollection<BsonDocument> Schedules => _database.GetCollection<BsonDocument>("Schedules");
/// <summary>
/// Конструктор
/// </summary>
public DataTransfer()
{
_client = new MongoClient(_mongoDBConnectionString);
_database = _client.GetDatabase(_databaseName);
}
/// <summary>
/// Начать перенос данных
/// </summary>
public void SyncData()
{
// Переносим данные
Transfer("Drivers");
Transfer("Transport");
Transfer("Routes");
Transfer("Stops");
Transfer("RouteStops");
Transfer("Schedules");
// Настраиваем корректные связи
var transportCollection = Transport.Find(Builders<BsonDocument>.Filter.Empty).ToList();
var routesCollection = Routes.Find(Builders<BsonDocument>.Filter.Empty).ToList();
var schedulesCollection = Schedules.Find(Builders<BsonDocument>.Filter.Empty).ToList();
// Связь между сущностями "Транспорт" и "Водитель"
transportCollection.ForEach(t =>
{
int tempDriverId = t.GetValue("DriverId").ToInt32();
var driverId = Drivers
.Find(Builders<BsonDocument>.Filter.Eq("Id", tempDriverId))
.FirstOrDefaultAsync()
.Result.GetValue("_id")
.ToString();
var driver = Drivers
.Find(Builders<BsonDocument>.Filter.Eq("Id", tempDriverId))
.Project(Builders<BsonDocument>.Projection.Exclude("Id"))
.FirstOrDefault();
var filter = Builders<BsonDocument>.Filter.Eq("_id", t.GetValue("_id"));
var updateDriverId = Builders<BsonDocument>.Update.Set("DriverId", driverId);
var updateDriver = Builders<BsonDocument>.Update.Set("Driver", driver);
Transport.UpdateOneAsync(filter, updateDriverId);
Transport.UpdateOneAsync(filter, updateDriver);
});
// Связь между сущностями "Маршрут" и "Транспорт"
routesCollection.ForEach(r =>
{
int tempTransportId = r.GetValue("TransportId").ToInt32();
var transportId = Transport
.Find(Builders<BsonDocument>.Filter.Eq("Id", tempTransportId))
.FirstOrDefaultAsync()
.Result.GetValue("_id")
.ToString();
var transport = Transport
.Find(Builders<BsonDocument>.Filter.Eq("Id", tempTransportId))
.Project(Builders<BsonDocument>.Projection.Exclude("Id"))
.FirstOrDefault();
var filter = Builders<BsonDocument>.Filter.Eq("_id", r.GetValue("_id"));
var updateTransportId = Builders<BsonDocument>.Update.Set("TransportId", transportId);
var updateTransport = Builders<BsonDocument>.Update.Set("Transport", transport);
Routes.UpdateOneAsync(filter, updateTransportId);
Routes.UpdateOneAsync(filter, updateTransport);
});
// Связь между сущностями "Маршруты" и "Остановки"
routesCollection.ForEach(r =>
{
var tempRouteId = r.GetValue("Id").ToInt32();
var routeStops = RouteStops
.Find(Builders<BsonDocument>.Filter.Eq("RouteId", tempRouteId))
.ToList();
var updateStops = new Dictionary<string, (BsonDocument, int)>();
routeStops.ForEach(rs =>
{
var tempStopId = rs.GetValue("StopId").ToInt32();
var stop = Stops
.Find(Builders<BsonDocument>.Filter.Eq("Id", tempStopId))
.Project(Builders<BsonDocument>.Projection.Exclude("Id"))
.FirstOrDefault();
if (stop != null)
{
var stopId = stop.GetValue("_id").ToString();
var stopNumber = rs.GetValue("Number").ToInt32();
updateStops.Add(stopId!, (stop, stopNumber));
}
});
var filter = Builders<BsonDocument>.Filter.Eq("_id", r.GetValue("_id"));
var update = Builders<BsonDocument>.Update.Set("Stops", updateStops);
Routes.UpdateOneAsync(filter, update);
});
// Связь между сущностями "Расписание" и "Маршрут"
schedulesCollection.ForEach(s =>
{
int tempRouteId = s.GetValue("RouteId").ToInt32();
var routeId = Routes
.Find(Builders<BsonDocument>.Filter.Eq("Id", tempRouteId))
.FirstOrDefaultAsync()
.Result.GetValue("_id")
.ToString();
var route = Routes
.Find(Builders<BsonDocument>.Filter.Eq("Id", tempRouteId))
.Project(Builders<BsonDocument>.Projection.Exclude("Id"))
.FirstOrDefault();
var filter = Builders<BsonDocument>.Filter.Eq("_id", s.GetValue("_id"));
var updateRouteId = Builders<BsonDocument>.Update.Set("RouteId", routeId);
var updateRoute = Builders<BsonDocument>.Update.Set("Route", route);
Schedules.UpdateOneAsync(filter, updateRouteId);
Schedules.UpdateOneAsync(filter, updateRoute);
});
// Убираем поле "Id"
var update = Builders<BsonDocument>.Update.Unset("Id");
Drivers.UpdateMany(new BsonDocument(), update);
Transport.UpdateMany(new BsonDocument(), update);
Routes.UpdateMany(new BsonDocument(), update);
Stops.UpdateMany(new BsonDocument(), update);
Schedules.UpdateMany(new BsonDocument(), update);
// Удаление коллекции для связи сущностей "Маршруты" и "Остановки"
RouteStops.Database.DropCollection("RouteStops");
}
/// <summary>
/// Перенос данных из таблицы в коллекцию
/// </summary>
/// <param name="collectionName"></param>
private void Transfer(string collectionName)
{
using var connection = new NpgsqlConnection(_pgsqlDBConnectionString);
connection.Open();
using var command = new NpgsqlCommand($"SELECT * FROM \"{collectionName}\"", connection);
using var reader = command.ExecuteReader();
var collection = _database.GetCollection<BsonDocument>(collectionName);
while (reader.Read())
{
var document = new BsonDocument();
for (int i = 0; i < reader.FieldCount; i++)
{
string fieldName = reader.GetName(i);
object value = reader.GetValue(i);
document.Add(fieldName, BsonValue.Create(value));
}
collection.InsertOne(document);
}
reader.Close();
command.Cancel();
connection.Close();
}
}
}

View File

@ -141,29 +141,20 @@ namespace RouteGuideMongoDBImplement.Implements
public RouteViewModel? Update(RouteBindingModel model)
{
using var context = new RouteGuideDatabase();
using var session = context._client.StartSession();
try
{
var filterBuilder = Builders<Route>.Filter;
var filter = filterBuilder.Eq(x => x.Id, model.Id);
var route = context.Routes.Find(filter).FirstOrDefault();
if (route == null)
{
return null;
}
var filterBuilder = Builders<Route>.Filter;
var filter = filterBuilder.Eq(x => x.Id, model.Id.ToString());
route.Update(model);
route.UpdateStops(context, model);
context.Routes.ReplaceOne(filter, route);
session.CommitTransaction();
return route.GetViewModel;
}
catch
var route = context.Routes.Find(filter).FirstOrDefault();
if (route == null)
{
session.AbortTransaction();
throw;
return null;
}
route.Update(model);
route.UpdateStops(context, model);
context.Routes.ReplaceOne(filter, route);
return route.GetViewModel;
}
/// <summary>

View File

@ -35,7 +35,7 @@ namespace RouteGuideMongoDBImplement.Models
/// Идентификатор транспорта
/// </summary>
[BsonRequired]
[BsonElement("transport_id")]
[BsonElement("TransportId")]
public string? TransportId { get; private set; }
/// <summary>

View File

@ -53,7 +53,7 @@ namespace RouteGuideMongoDBImplement.Models
/// Идентификатор маршрута
/// </summary>
[BsonRequired]
[BsonElement("route_id")]
[BsonElement("RouteId")]
public string? RouteId { get; private set; }
/// <summary>

View File

@ -48,7 +48,7 @@ namespace RouteGuideMongoDBImplement.Models
/// Идентификатор водителя
/// </summary>
[BsonRequired]
[BsonElement("driver_id")]
[BsonElement("DriverId")]
public string? DriverId { get; private set; }
/// <summary>

View File

@ -14,6 +14,7 @@
<ItemGroup>
<PackageReference Include="MongoDB.Bson" Version="2.25.0" />
<PackageReference Include="MongoDB.Driver" Version="2.25.0" />
<PackageReference Include="Npgsql" Version="7.0.4" />
</ItemGroup>
</Project>

View File

@ -20,203 +20,215 @@
base.Dispose(disposing);
}
#region Windows Form Designer generated code
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
menuStrip1 = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem();
DrviversToolStripMenuItem = new ToolStripMenuItem();
TransportToolStripMenuItem = new ToolStripMenuItem();
RoutesToolStripMenuItem = new ToolStripMenuItem();
StopsToolStripMenuItem = new ToolStripMenuItem();
тестыToolStripMenuItem = new ToolStripMenuItem();
DriversTestsToolStripMenuItem = new ToolStripMenuItem();
TransportTestsToolStripMenuItem = new ToolStripMenuItem();
RoutesTestsToolStripMenuItem = new ToolStripMenuItem();
StopsTestsToolStripMenuItem = new ToolStripMenuItem();
SchedulesTestsToolStripMenuItem = new ToolStripMenuItem();
buttonCreate = new Button();
buttonUpdate = new Button();
buttonDelete = new Button();
buttonRefresh = new Button();
dataGridView = new DataGridView();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, тестыToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(984, 24);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DrviversToolStripMenuItem, TransportToolStripMenuItem, RoutesToolStripMenuItem, StopsToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(97, 20);
справочникиToolStripMenuItem.Text = " Справочники";
//
// DrviversToolStripMenuItem
//
DrviversToolStripMenuItem.Name = "DrviversToolStripMenuItem";
DrviversToolStripMenuItem.Size = new Size(136, 22);
DrviversToolStripMenuItem.Text = "Водители";
DrviversToolStripMenuItem.Click += DrviversToolStripMenuItem_Click;
//
// TransportToolStripMenuItem
//
TransportToolStripMenuItem.Name = "TransportToolStripMenuItem";
TransportToolStripMenuItem.Size = new Size(136, 22);
TransportToolStripMenuItem.Text = "Транспорт";
TransportToolStripMenuItem.Click += TransportToolStripMenuItem_Click;
//
// RoutesToolStripMenuItem
//
RoutesToolStripMenuItem.Name = "RoutesToolStripMenuItem";
RoutesToolStripMenuItem.Size = new Size(136, 22);
RoutesToolStripMenuItem.Text = "Маршруты";
RoutesToolStripMenuItem.Click += RoutesToolStripMenuItem_Click;
//
// StopsToolStripMenuItem
//
StopsToolStripMenuItem.Name = "StopsToolStripMenuItem";
StopsToolStripMenuItem.Size = new Size(136, 22);
StopsToolStripMenuItem.Text = "Остановки";
StopsToolStripMenuItem.Click += StopsToolStripMenuItem_Click;
//
// тестыToolStripMenuItem
//
тестыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DriversTestsToolStripMenuItem, TransportTestsToolStripMenuItem, RoutesTestsToolStripMenuItem, StopsTestsToolStripMenuItem, SchedulesTestsToolStripMenuItem });
тестыToolStripMenuItem.Name = естыToolStripMenuItem";
тестыToolStripMenuItem.Size = new Size(51, 20);
тестыToolStripMenuItem.Text = "Тесты";
//
// DriversTestsToolStripMenuItem
//
DriversTestsToolStripMenuItem.Name = "DriversTestsToolStripMenuItem";
DriversTestsToolStripMenuItem.Size = new Size(180, 22);
DriversTestsToolStripMenuItem.Text = "Водители";
DriversTestsToolStripMenuItem.Click += DriversTestsToolStripMenuItem_Click;
//
// TransportTestsToolStripMenuItem
//
TransportTestsToolStripMenuItem.Name = "TransportTestsToolStripMenuItem";
TransportTestsToolStripMenuItem.Size = new Size(180, 22);
TransportTestsToolStripMenuItem.Text = "Транспорт";
TransportTestsToolStripMenuItem.Click += TransportTestsToolStripMenuItem_Click;
//
// RoutesTestsToolStripMenuItem
//
RoutesTestsToolStripMenuItem.Name = "RoutesTestsToolStripMenuItem";
RoutesTestsToolStripMenuItem.Size = new Size(180, 22);
RoutesTestsToolStripMenuItem.Text = "Маршруты";
RoutesTestsToolStripMenuItem.Click += RoutesTestsToolStripMenuItem_Click;
//
// StopsTestsToolStripMenuItem
//
StopsTestsToolStripMenuItem.Name = "StopsTestsToolStripMenuItem";
StopsTestsToolStripMenuItem.Size = new Size(180, 22);
StopsTestsToolStripMenuItem.Text = "Остановки";
StopsTestsToolStripMenuItem.Click += StopsTestsToolStripMenuItem_Click;
//
// SchedulesTestsToolStripMenuItem
//
SchedulesTestsToolStripMenuItem.Name = "SchedulesTestsToolStripMenuItem";
SchedulesTestsToolStripMenuItem.Size = new Size(180, 22);
SchedulesTestsToolStripMenuItem.Text = "Расписания";
SchedulesTestsToolStripMenuItem.Click += SchedulesTestsToolStripMenuItem_Click;
//
// buttonCreate
//
buttonCreate.Location = new Point(885, 37);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(75, 23);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(885, 66);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(75, 23);
buttonUpdate.TabIndex = 2;
buttonUpdate.Text = "Изменить";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += buttonUpdate_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(885, 95);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(75, 23);
buttonDelete.TabIndex = 3;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += buttonDelete_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(885, 124);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(75, 23);
buttonRefresh.TabIndex = 4;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += buttonRefresh_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Left;
dataGridView.Location = new Point(0, 24);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowTemplate.Height = 25;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(850, 337);
dataGridView.TabIndex = 5;
//
// FormMain
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(984, 361);
Controls.Add(dataGridView);
Controls.Add(buttonRefresh);
Controls.Add(buttonDelete);
Controls.Add(buttonUpdate);
Controls.Add(buttonCreate);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormMain";
Text = "Расписание";
Load += FormMain_Load;
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
menuStrip1 = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem();
DrviversToolStripMenuItem = new ToolStripMenuItem();
TransportToolStripMenuItem = new ToolStripMenuItem();
RoutesToolStripMenuItem = new ToolStripMenuItem();
StopsToolStripMenuItem = new ToolStripMenuItem();
тестыToolStripMenuItem = new ToolStripMenuItem();
DriversTestsToolStripMenuItem = new ToolStripMenuItem();
TransportTestsToolStripMenuItem = new ToolStripMenuItem();
RoutesTestsToolStripMenuItem = new ToolStripMenuItem();
StopsTestsToolStripMenuItem = new ToolStripMenuItem();
SchedulesTestsToolStripMenuItem = new ToolStripMenuItem();
buttonCreate = new Button();
buttonUpdate = new Button();
buttonDelete = new Button();
buttonRefresh = new Button();
dataGridView = new DataGridView();
buttonSyncData = new Button();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, тестыToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(984, 24);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DrviversToolStripMenuItem, TransportToolStripMenuItem, RoutesToolStripMenuItem, StopsToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(97, 20);
справочникиToolStripMenuItem.Text = " Справочники";
//
// DrviversToolStripMenuItem
//
DrviversToolStripMenuItem.Name = "DrviversToolStripMenuItem";
DrviversToolStripMenuItem.Size = new Size(136, 22);
DrviversToolStripMenuItem.Text = "Водители";
DrviversToolStripMenuItem.Click += DrviversToolStripMenuItem_Click;
//
// TransportToolStripMenuItem
//
TransportToolStripMenuItem.Name = "TransportToolStripMenuItem";
TransportToolStripMenuItem.Size = new Size(136, 22);
TransportToolStripMenuItem.Text = "Транспорт";
TransportToolStripMenuItem.Click += TransportToolStripMenuItem_Click;
//
// RoutesToolStripMenuItem
//
RoutesToolStripMenuItem.Name = "RoutesToolStripMenuItem";
RoutesToolStripMenuItem.Size = new Size(136, 22);
RoutesToolStripMenuItem.Text = "Маршруты";
RoutesToolStripMenuItem.Click += RoutesToolStripMenuItem_Click;
//
// StopsToolStripMenuItem
//
StopsToolStripMenuItem.Name = "StopsToolStripMenuItem";
StopsToolStripMenuItem.Size = new Size(136, 22);
StopsToolStripMenuItem.Text = "Остановки";
StopsToolStripMenuItem.Click += StopsToolStripMenuItem_Click;
//
// тестыToolStripMenuItem
//
тестыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DriversTestsToolStripMenuItem, TransportTestsToolStripMenuItem, RoutesTestsToolStripMenuItem, StopsTestsToolStripMenuItem, SchedulesTestsToolStripMenuItem });
тестыToolStripMenuItem.Name = естыToolStripMenuItem";
тестыToolStripMenuItem.Size = new Size(51, 20);
тестыToolStripMenuItem.Text = "Тесты";
//
// DriversTestsToolStripMenuItem
//
DriversTestsToolStripMenuItem.Name = "DriversTestsToolStripMenuItem";
DriversTestsToolStripMenuItem.Size = new Size(139, 22);
DriversTestsToolStripMenuItem.Text = "Водители";
DriversTestsToolStripMenuItem.Click += DriversTestsToolStripMenuItem_Click;
//
// TransportTestsToolStripMenuItem
//
TransportTestsToolStripMenuItem.Name = "TransportTestsToolStripMenuItem";
TransportTestsToolStripMenuItem.Size = new Size(139, 22);
TransportTestsToolStripMenuItem.Text = "Транспорт";
TransportTestsToolStripMenuItem.Click += TransportTestsToolStripMenuItem_Click;
//
// RoutesTestsToolStripMenuItem
//
RoutesTestsToolStripMenuItem.Name = "RoutesTestsToolStripMenuItem";
RoutesTestsToolStripMenuItem.Size = new Size(139, 22);
RoutesTestsToolStripMenuItem.Text = "Маршруты";
RoutesTestsToolStripMenuItem.Click += RoutesTestsToolStripMenuItem_Click;
//
// StopsTestsToolStripMenuItem
//
StopsTestsToolStripMenuItem.Name = "StopsTestsToolStripMenuItem";
StopsTestsToolStripMenuItem.Size = new Size(139, 22);
StopsTestsToolStripMenuItem.Text = "Остановки";
StopsTestsToolStripMenuItem.Click += StopsTestsToolStripMenuItem_Click;
//
// SchedulesTestsToolStripMenuItem
//
SchedulesTestsToolStripMenuItem.Name = "SchedulesTestsToolStripMenuItem";
SchedulesTestsToolStripMenuItem.Size = new Size(139, 22);
SchedulesTestsToolStripMenuItem.Text = "Расписания";
SchedulesTestsToolStripMenuItem.Click += SchedulesTestsToolStripMenuItem_Click;
//
// buttonCreate
//
buttonCreate.Location = new Point(885, 37);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(75, 23);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(885, 66);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(75, 23);
buttonUpdate.TabIndex = 2;
buttonUpdate.Text = "Изменить";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += buttonUpdate_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(885, 95);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(75, 23);
buttonDelete.TabIndex = 3;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += buttonDelete_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(885, 124);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(75, 23);
buttonRefresh.TabIndex = 4;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += buttonRefresh_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Left;
dataGridView.Location = new Point(0, 24);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowTemplate.Height = 25;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(850, 337);
dataGridView.TabIndex = 5;
//
// buttonSyncData
//
buttonSyncData.Location = new Point(885, 309);
buttonSyncData.Name = "buttonSyncData";
buttonSyncData.Size = new Size(75, 40);
buttonSyncData.TabIndex = 6;
buttonSyncData.Text = "Синхр. данные";
buttonSyncData.UseVisualStyleBackColor = true;
buttonSyncData.Click += buttonSyncData_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(984, 361);
Controls.Add(buttonSyncData);
Controls.Add(dataGridView);
Controls.Add(buttonRefresh);
Controls.Add(buttonDelete);
Controls.Add(buttonUpdate);
Controls.Add(buttonCreate);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormMain";
Text = "Расписание";
Load += FormMain_Load;
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
#endregion
private MenuStrip menuStrip1;
private MenuStrip menuStrip1;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem DrviversToolStripMenuItem;
private ToolStripMenuItem TransportToolStripMenuItem;
@ -233,5 +245,6 @@
private ToolStripMenuItem RoutesTestsToolStripMenuItem;
private ToolStripMenuItem StopsTestsToolStripMenuItem;
private ToolStripMenuItem SchedulesTestsToolStripMenuItem;
}
private Button buttonSyncData;
}
}

View File

@ -2,273 +2,285 @@ using Microsoft.Extensions.Logging;
using RouteGuideBusinessLogics.BusinessLogics;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.BusinessLogicsContracts;
using RouteGuideMongoDBImplement;
namespace RouteGuideView
{
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà ðàñïèñàíèé
/// </summary>
public partial class FormMain : Form
{
/// <summary>
/// Ëîããåð
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà ðàñïèñàíèé
/// </summary>
public partial class FormMain : Form
{
/// <summary>
/// Ëîããåð
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Áèçíåñ-ëîãèêà äëÿ ðàñïèñàíèé
/// </summary>
private readonly IScheduleLogic _schedulelogic;
/// <summary>
/// Áèçíåñ-ëîãèêà äëÿ ðàñïèñàíèé
/// </summary>
private readonly IScheduleLogic _schedulelogic;
/// <summary>
/// Êîíñòðóêòîð
/// </summary>
/// <param name="logger"></param>
/// <param name="scheduleLogic"></param>
public FormMain(ILogger<FormMain> logger, IScheduleLogic scheduleLogic)
{
InitializeComponent();
_logger = logger;
_schedulelogic = scheduleLogic;
}
/// <summary>
/// Êîíñòðóêòîð
/// </summary>
/// <param name="logger"></param>
/// <param name="scheduleLogic"></param>
public FormMain(ILogger<FormMain> logger, IScheduleLogic scheduleLogic)
{
InitializeComponent();
_logger = logger;
_schedulelogic = scheduleLogic;
}
/// <summary>
/// Çàãðóçêà äàííûõ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
/// <summary>
/// Çàãðóçêà äàííûõ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà âîäèòåëåé
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DrviversToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormDrivers));
if (service is FormDrivers form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà âîäèòåëåé
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DrviversToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormDrivers));
if (service is FormDrivers form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà òðàíñïîðòà
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TransportToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormTransports));
if (service is FormTransports form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà òðàíñïîðòà
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TransportToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormTransports));
if (service is FormTransports form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà ìàðøðóòîâ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RoutesToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormRoutes));
if (service is FormRoutes form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà ìàðøðóòîâ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RoutesToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormRoutes));
if (service is FormRoutes form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà îñòàíîâîê
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StopsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormStops));
if (service is FormStops form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ âûâîäà ñïèñêà îñòàíîâîê
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StopsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormStops));
if (service is FormStops form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Âîäèòåëü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DriversTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormDriversTests));
if (service is FormDriversTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Âîäèòåëü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DriversTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormDriversTests));
if (service is FormDriversTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Òðàíñïîðò"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TransportTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormTransportTests));
if (service is FormTransportTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Òðàíñïîðò"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TransportTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormTransportTests));
if (service is FormTransportTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Ìàðøðóò"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RoutesTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormRoutesTests));
if (service is FormRoutesTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Ìàðøðóò"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RoutesTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormRoutesTests));
if (service is FormRoutesTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Îñòàíîâêà"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StopsTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormStopsTests));
if (service is FormStopsTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Îñòàíîâêà"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StopsTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormStopsTests));
if (service is FormStopsTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Ðàñïèñàíèå"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SchedulesTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSchedulesTests));
if (service is FormSchedulesTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Ôîðìà äëÿ òåñòîâ ñóùíîñòè "Ðàñïèñàíèå"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SchedulesTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSchedulesTests));
if (service is FormSchedulesTests form)
{
form.ShowDialog();
}
}
/// <summary>
/// Êíîïêà "Ñîçäàòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSchedule));
if (service is FormSchedule form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
/// <summary>
/// Êíîïêà "Ñîçäàòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSchedule));
if (service is FormSchedule form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
/// <summary>
/// Êíîïêà "Èçìåíèòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonUpdate_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSchedule));
if (service is FormSchedule form)
{
form.Id = dataGridView.SelectedRows[0].Cells["Id"].Value;
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
/// <summary>
/// Êíîïêà "Èçìåíèòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonUpdate_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSchedule));
if (service is FormSchedule form)
{
form.Id = dataGridView.SelectedRows[0].Cells["Id"].Value;
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
/// <summary>
/// Êíîïêà "Óäàëèòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonDelete_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Óäàëèòü çàïèñü?", "Âîïðîñ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
object id = dataGridView.SelectedRows[0].Cells["Id"].Value;
_logger.LogInformation("Óäàëåíèå ñóùíîñòè 'Ðàñïèñàíèå'");
/// <summary>
/// Êíîïêà "Óäàëèòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonDelete_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Óäàëèòü çàïèñü?", "Âîïðîñ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
object id = dataGridView.SelectedRows[0].Cells["Id"].Value;
_logger.LogInformation("Óäàëåíèå ñóùíîñòè 'Ðàñïèñàíèå'");
try
{
if (!_schedulelogic.Delete(new ScheduleBindingModel { Id = id }))
{
throw new Exception("Îøèáêà ïðè óäàëåíèè ñóùíîñòè 'Ðàñïèñàíèå'. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Îøèáêà óäàëåíèÿ ñóùíîñòè 'Ðàñïèñàíèå'");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
try
{
if (!_schedulelogic.Delete(new ScheduleBindingModel { Id = id }))
{
throw new Exception("Îøèáêà ïðè óäàëåíèè ñóùíîñòè 'Ðàñïèñàíèå'. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(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)
{
LoadData();
}
/// <summary>
/// Êíîïêà "Îáíîâèòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRefresh_Click(object sender, EventArgs e)
{
LoadData();
}
/// <summary>
/// Çàãðóçêà äàííûõ
/// </summary>
private void LoadData()
{
try
{
var list = _schedulelogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["RouteId"].Visible = false;
dataGridView.Columns["RouteName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Çàãðóçêà ñïèñêà ðàñïèñàíèé");
}
catch (Exception ex)
{
_logger.LogError(ex, "Îøèáêà çàãðóçêè ñïèñêà ðàñïèñàíèé");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Êíîïêà "Ñèíõðîíèçèðîâàòü äàííûå"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSyncData_Click(object sender, EventArgs e)
{
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.SyncData();
}
/// <summary>
/// Çàãðóçêà äàííûõ
/// </summary>
private void LoadData()
{
try
{
var list = _schedulelogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["RouteId"].Visible = false;
dataGridView.Columns["RouteName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Çàãðóçêà ñïèñêà ðàñïèñàíèé");
}
catch (Exception ex)
{
_logger.LogError(ex, "Îøèáêà çàãðóçêè ñïèñêà ðàñïèñàíèé");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}