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) public RouteViewModel? Update(RouteBindingModel model)
{ {
using var context = new RouteGuideDatabase(); 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(); var filterBuilder = Builders<Route>.Filter;
if (route == null) var filter = filterBuilder.Eq(x => x.Id, model.Id.ToString());
{
return null;
}
route.Update(model); var route = context.Routes.Find(filter).FirstOrDefault();
route.UpdateStops(context, model); if (route == null)
context.Routes.ReplaceOne(filter, route);
session.CommitTransaction();
return route.GetViewModel;
}
catch
{ {
session.AbortTransaction(); return null;
throw;
} }
route.Update(model);
route.UpdateStops(context, model);
context.Routes.ReplaceOne(filter, route);
return route.GetViewModel;
} }
/// <summary> /// <summary>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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