восстанолвение из бекапа

This commit is contained in:
kotcheshir73 2021-04-02 20:04:46 +04:00
parent 1a027e7583
commit 356c8a6d02
9 changed files with 525 additions and 109 deletions

View File

@ -24,8 +24,8 @@ GO";
SELECT Id, RoleName, RolePriority, DateCreate, DateDelete, IsDeleted FROM DepartmentDatabaseContext.dbo.DepartmentRoles"; SELECT Id, RoleName, RolePriority, DateCreate, DateDelete, IsDeleted FROM DepartmentDatabaseContext.dbo.DepartmentRoles";
private static readonly string userMigration = private static readonly string userMigration =
@"INSERT INTO DepartmentDatabasePortal.dbo.Users(Id, UserName, PasswordHash, StudentId, LecturerId, Avatar, DateLastVisit, IsBanned, DateBanned, CountAttempt, DateCreate, DateDelete, IsDeleted) @"INSERT INTO DepartmentDatabasePortal.dbo.Users(Id, UserName, PasswordHash, Avatar, DateLastVisit, IsBanned, DateBanned, CountAttempt, DateCreate, DateDelete, IsDeleted)
SELECT Id, UserName, PasswordHash, StudentId, LecturerId, Avatar, DateLastVisit, IsLocked, DateBanned, CountAttempt, DateCreate, DateDelete, IsDeleted FROM DepartmentDatabaseContext.dbo.DepartmentUsers"; SELECT Id, UserName, PasswordHash, Avatar, DateLastVisit, IsLocked, DateBanned, CountAttempt, DateCreate, DateDelete, IsDeleted FROM DepartmentDatabaseContext.dbo.DepartmentUsers";
private static readonly string userroleMigration = private static readonly string userroleMigration =
@"INSERT INTO DepartmentDatabasePortal.dbo.UserRoles(Id, UserId, RoleId, DateCreate, DateDelete, IsDeleted) @"INSERT INTO DepartmentDatabasePortal.dbo.UserRoles(Id, UserId, RoleId, DateCreate, DateDelete, IsDeleted)

View File

@ -19,5 +19,10 @@
/// Создать архив с выгрузкой /// Создать архив с выгрузкой
/// </summary> /// </summary>
public bool CreateArchive { get; set; } public bool CreateArchive { get; set; }
/// <summary>
/// Имя файла для архива
/// </summary>
public string ArchiveFileName { get; set; }
} }
} }

View File

@ -1,14 +1,13 @@
using ModuleTools.BusinessLogics; using ModuleTools.BusinessLogics;
using ModuleTools.Enums; using ModuleTools.Enums;
using ModuleTools.Extensions;
using ModuleTools.Interfaces; using ModuleTools.Interfaces;
using ModuleTools.Models; using ModuleTools.Models;
using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.BindingModels;
using SecurityBusinessLogic.Interfaces; using SecurityBusinessLogic.Interfaces;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace SecurityBusinessLogic.BusinessLogics namespace SecurityBusinessLogic.BusinessLogics
{ {
@ -17,18 +16,25 @@ namespace SecurityBusinessLogic.BusinessLogics
/// </summary> /// </summary>
public class BackupBusinessLogic public class BackupBusinessLogic
{ {
private IBackupService _service; /// <summary>
/// Серивс для работы с бекапом
/// </summary>
private readonly IBackupService _service;
/// <summary> /// <summary>
/// Менеджер безопасности /// Менеджер безопасности
/// </summary> /// </summary>
private ISecurityManager _security; private readonly ISecurityManager _security;
/// <summary> /// <summary>
/// Перечень ошибок при выполнении операции /// Перечень ошибок при выполнении операции
/// </summary> /// </summary>
public List<(string Title, string Message)> Errors { get; protected set; } public List<(string Title, string Message)> Errors { get; protected set; }
/// <summary>
/// Логика работы с бекапом
/// </summary>
/// <param name="service"></param>
public BackupBusinessLogic(IBackupService service) public BackupBusinessLogic(IBackupService service)
{ {
_service = service; _service = service;
@ -36,19 +42,80 @@ namespace SecurityBusinessLogic.BusinessLogics
Errors = new(); Errors = new();
} }
/// <summary>
/// Создание бекапа с данными
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool CreateBackUp(BackupBindingModel model) public bool CreateBackUp(BackupBindingModel model)
{ {
if (NoAccess()) if (model.FolderName.IsEmpty())
{ {
Errors.Add(("Ошибка", "Путь до папки не указан"));
return false; return false;
} }
var result = _service.CreateBackUp(model); try
if (!result.IsSucceeded)
{ {
Errors.AddRange(result.Errors); if (NoAccess())
{
return false;
}
var result = _service.CreateBackUp(model);
if (!result.IsSucceeded)
{
Errors.AddRange(result.Errors);
return false;
}
return true;
}
catch (Exception ex)
{
Errors.Add(("Ошибка", ex.Message));
return false;
}
}
/// <summary>
/// Восстанволение данных через бекап
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool RestoreBackUp(BackupBindingModel model)
{
if (model.FolderName.IsEmpty() && model.ArchiveFileName.IsEmpty())
{
Errors.Add(("Ошибка", "Путь до папки/архива не указан"));
return false;
}
if (model.ArchiveFileName.IsNotEmpty() && !File.Exists(model.ArchiveFileName))
{
Errors.Add(("Ошибка", "Файл с архивом не найден"));
return false;
}
if (model.ArchiveFileName.IsEmpty() && !Directory.Exists(model.FolderName))
{
Errors.Add(("Ошибка", "Папка с даными не найдена"));
return false;
}
try
{
if (NoAccess())
{
return false;
}
var result = _service.RestoreBackUp(model);
if (!result.IsSucceeded)
{
Errors.AddRange(result.Errors);
return false;
}
return true;
}
catch (Exception ex)
{
Errors.Add(("Ошибка", ex.Message));
return false; return false;
} }
return true;
} }
/// <summary> /// <summary>
@ -57,7 +124,7 @@ namespace SecurityBusinessLogic.BusinessLogics
/// <returns></returns> /// <returns></returns>
private bool NoAccess() private bool NoAccess()
{ {
if (_security.CheckAccess(new SecurityManagerCheckAccessModel(null, AccessOperation.РаботасБекапом, AccessType.View, "бекап"))) if (_security.CheckAccess(new SecurityManagerCheckAccessModel(null, AccessOperation.РаботасБекапом, AccessType.Delete, "бекап")))
{ {
return false; return false;
} }

View File

@ -8,6 +8,18 @@ namespace SecurityBusinessLogic.Interfaces
/// </summary> /// </summary>
public interface IBackupService public interface IBackupService
{ {
/// <summary>
/// Создание бекапа с данными
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
OperationResultModel CreateBackUp(BackupBindingModel model); OperationResultModel CreateBackUp(BackupBindingModel model);
/// <summary>
/// Восстанволение данных через бекап
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
OperationResultModel RestoreBackUp(BackupBindingModel model);
} }
} }

View File

@ -0,0 +1,201 @@
using DatabaseCore;
using ModuleTools.Attributes;
using ModuleTools.Extensions;
using ModuleTools.Interfaces;
using ModuleTools.Models;
using SecurityBusinessLogic.BindingModels;
using SecurityBusinessLogic.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Json;
namespace SecurityDatabaseImplementation.Implementations
{
/// <summary>
/// Реализация IBackupService для сохранения в JSON через JsonContract
/// </summary>
public class BackupJsonContractService : IBackupService
{
public OperationResultModel CreateBackUp(BackupBindingModel model)
{
try
{
var asm = typeof(DatabaseManager).Assembly;
MethodInfo method = GetType().GetTypeInfo().GetDeclaredMethod("SaveToFile");
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEntitySecurityExtenstion<>)) &&
t.GetCustomAttribute<EntityDescriptionAttribute>() != null)
{
MethodInfo generic = method.MakeGenericMethod(t);
generic.Invoke(this, new object[] { model.FolderName, model.FullData, t });
}
}
if (model.CreateArchive)
{
var fileName = $"{model.FolderName}.zip";
if (File.Exists(fileName))
{
File.Delete($"{model.FolderName}.zip");
}
ZipFile.CreateFromDirectory(model.FolderName, fileName);
}
}
catch (Exception ex)
{
return OperationResultModel.Error(ex);
}
return OperationResultModel.Success(null);
}
public OperationResultModel RestoreBackUp(BackupBindingModel model)
{
try
{
if (model.ArchiveFileName.IsNotEmpty())
{
if(model.FolderName.IsEmpty())
{
model.FolderName = $"{Path.GetDirectoryName(model.ArchiveFileName)}{Path.GetFileNameWithoutExtension(model.ArchiveFileName)}";
}
ZipFile.ExtractToDirectory(model.ArchiveFileName, model.FolderName);
}
var asm = typeof(DatabaseManager).Assembly;
#region вытаскиваем все типы-сущности (они должны быть унаследованы от IEntitySecurityExtenstion и иметь атрибут EntityDescription)
List<Type> types = new();
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEntitySecurityExtenstion<>)) &&
t.GetCustomAttribute<EntityDescriptionAttribute>() != null)
{
types.Add(t);
}
}
#endregion
#region формиурем зависимости (в каком порядке загружать данные)
Dictionary<Type, int> typesWithLevel = new();
while (types.Count > 0)
{
for (int i = 0; i < types.Count; ++i)
{
var depends = types[i].GetCustomAttributes<EntityDependencyAttribute>();
if ((depends == null || !depends.Any()) && !typesWithLevel.ContainsKey(types[i]))
{
typesWithLevel.Add(types[i], 0);
types.RemoveAt(i--);
continue;
}
int? level = null;
foreach (var depend in depends)
{
var type = typesWithLevel.Keys.FirstOrDefault(x => x.Name == depend.ClassName);
if (type != null)
{
if (!level.HasValue)
{
level = typesWithLevel[type];
}
else if (level < typesWithLevel[type])
{
level = typesWithLevel[type];
}
}
else
{
level = null;
break;
}
}
if (level.HasValue)
{
typesWithLevel.Add(types[i], level.Value + 1);
types.RemoveAt(i--);
continue;
}
}
}
#endregion
#region Удаляем записи сначала из тех, на которые никкто не ссылается и в последнюю оередь, те, на которые все ссылаются
var deleteOrder = typesWithLevel.OrderByDescending(x => x.Value);
MethodInfo delMethod = GetType().GetTypeInfo().GetDeclaredMethod("DeleteFromDB");
foreach (var delElem in deleteOrder)
{
if (File.Exists(string.Format("{0}/{1}.json", model.FolderName, delElem.Key.Name)))
{
MethodInfo generic = delMethod.MakeGenericMethod(delElem.Key);
generic.Invoke(this, null);
}
}
#endregion
#region Заполняем в порядке - сначала те, у которых нет родителей, потом их потомство
MethodInfo method = GetType().GetTypeInfo().GetDeclaredMethod("LoadFromFile");
foreach (var delElem in typesWithLevel.OrderBy(x => x.Value))
{
MethodInfo generic = method.MakeGenericMethod(delElem.Key);
generic.Invoke(this, new object[] { model.FolderName, delElem.Key });
}
#endregion
}
catch (Exception ex)
{
return OperationResultModel.Error(ex);
}
return OperationResultModel.Success(null);
}
/// <summary>
/// Сохранение списка сущности из БД в файл (вызывается через рефлексию)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="folderName"></param>
/// <param name="allowFullData"></param>
/// <param name="t"></param>
private void SaveToFile<T>(string folderName, bool allowFullData, Type t) where T : class, IEntitySecurityExtenstion<T>, new()
{
using var context = DatabaseManager.GetContext;
var records = context.Set<T>().Select(x => x.SecurityCheck(x, allowFullData));
DataContractJsonSerializer jsonFormatter = new(typeof(List<T>));
using FileStream fs = new(string.Format("{0}/{1}.json", folderName, t.Name), FileMode.OpenOrCreate);
jsonFormatter.WriteObject(fs, records);
}
/// <summary>
/// Отчистка записей сущности в БД (вызывается через рефлексию)
/// </summary>
/// <typeparam name="T"></typeparam>
private void DeleteFromDB<T>() where T : class, new()
{
using var context = DatabaseManager.GetContext;
context.Set<T>().RemoveRange(context.Set<T>());
context.SaveChanges();
}
/// <summary>
/// Загрузка списка сущности из файла в БД (вызывается через рефлексию)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="folderName"></param>
/// <param name="t"></param>
private void LoadFromFile<T>(string folderName, Type t) where T : class, new()
{
using var context = DatabaseManager.GetContext;
if (File.Exists(string.Format("{0}/{1}.json", folderName, t.Name)))
{
DataContractJsonSerializer jsonFormatter = new(typeof(List<T>));
using FileStream fs = new(string.Format("{0}/{1}.json", folderName, t.Name), FileMode.Open);
List<T> records = (List<T>)jsonFormatter.ReadObject(fs);
context.Set<T>().AddRange(records);
context.SaveChanges();
}
}
}
}

View File

@ -1,54 +0,0 @@
using DatabaseCore;
using ModuleTools.Interfaces;
using ModuleTools.Models;
using SecurityBusinessLogic.BindingModels;
using SecurityBusinessLogic.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Json;
namespace SecurityDatabaseImplementation.Implementations
{
public class BackupService : IBackupService
{
public OperationResultModel CreateBackUp(BackupBindingModel model)
{
try
{
var asm = typeof(DatabaseManager).Assembly;
MethodInfo method = GetType().GetTypeInfo().GetDeclaredMethod("SaveToFile");
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEntitySecurityExtenstion<>)))
{
var elem = asm.CreateInstance(t.FullName);
MethodInfo generic = method.MakeGenericMethod(elem.GetType());
generic.Invoke(this, new object[] { model.FolderName, model.FullData, t });
}
}
if (model.CreateArchive)
{
ZipFile.CreateFromDirectory(model.FolderName, $"{model.FolderName}.zip");
}
}
catch (Exception ex)
{
return OperationResultModel.Error(ex);
}
return OperationResultModel.Success(null);
}
private void SaveToFile<T>(string folderName, bool allowFullData, Type t) where T : class, IEntitySecurityExtenstion<T>, new()
{
using var context = DatabaseManager.GetContext;
var records = context.Set<T>().Select(x => x.SecurityCheck(x, allowFullData));
DataContractJsonSerializer jsonFormatter = new(typeof(List<T>));
using FileStream fs = new(string.Format("{0}/{1}.json", folderName, t.Name), FileMode.OpenOrCreate);
jsonFormatter.WriteObject(fs, records);
}
}
}

View File

@ -15,7 +15,7 @@ namespace SecurityDatabaseImplementation
DependencyManager.Instance.RegisterType<IUserService, UserService>(); DependencyManager.Instance.RegisterType<IUserService, UserService>();
DependencyManager.Instance.RegisterType<IUserRoleService, UserRoleService>(); DependencyManager.Instance.RegisterType<IUserRoleService, UserRoleService>();
DependencyManager.Instance.RegisterType<IBackupService, BackupService>(); DependencyManager.Instance.RegisterType<IBackupService, BackupJsonContractService>();
} }
} }
} }

View File

@ -33,13 +33,22 @@ namespace SecurityWindowsDesktop.SpecialControls
this.buttonCreateBackup = new System.Windows.Forms.Button(); this.buttonCreateBackup = new System.Windows.Forms.Button();
this.checkBoxCreateArchive = new System.Windows.Forms.CheckBox(); this.checkBoxCreateArchive = new System.Windows.Forms.CheckBox();
this.checkBoxFullLoad = new System.Windows.Forms.CheckBox(); this.checkBoxFullLoad = new System.Windows.Forms.CheckBox();
this.buttonSelectFolder = new System.Windows.Forms.Button(); this.buttonSaveSelectFolder = new System.Windows.Forms.Button();
this.textBoxFolderName = new System.Windows.Forms.TextBox(); this.textBoxSaveFolderName = new System.Windows.Forms.TextBox();
this.labelFolderName = new System.Windows.Forms.Label(); this.labelSaveFolderName = new System.Windows.Forms.Label();
this.toolStripHeader = new System.Windows.Forms.ToolStrip(); this.toolStripHeader = new System.Windows.Forms.ToolStrip();
this.toolStripButtonClose = new System.Windows.Forms.ToolStripButton(); this.toolStripButtonClose = new System.Windows.Forms.ToolStripButton();
this.groupBoxLoadBackup = new System.Windows.Forms.GroupBox();
this.buttonRestoreBackup = new System.Windows.Forms.Button();
this.buttonLoadArchiveSelect = new System.Windows.Forms.Button();
this.textBoxLoadArchiveName = new System.Windows.Forms.TextBox();
this.labelLoadArchiveName = new System.Windows.Forms.Label();
this.buttonLoadSelectFolder = new System.Windows.Forms.Button();
this.textBoxLoadFolderName = new System.Windows.Forms.TextBox();
this.labelLoadFolderName = new System.Windows.Forms.Label();
this.groupBoxSaveBackup.SuspendLayout(); this.groupBoxSaveBackup.SuspendLayout();
this.toolStripHeader.SuspendLayout(); this.toolStripHeader.SuspendLayout();
this.groupBoxLoadBackup.SuspendLayout();
this.SuspendLayout(); this.SuspendLayout();
// //
// groupBoxSaveBackup // groupBoxSaveBackup
@ -47,9 +56,9 @@ namespace SecurityWindowsDesktop.SpecialControls
this.groupBoxSaveBackup.Controls.Add(this.buttonCreateBackup); this.groupBoxSaveBackup.Controls.Add(this.buttonCreateBackup);
this.groupBoxSaveBackup.Controls.Add(this.checkBoxCreateArchive); this.groupBoxSaveBackup.Controls.Add(this.checkBoxCreateArchive);
this.groupBoxSaveBackup.Controls.Add(this.checkBoxFullLoad); this.groupBoxSaveBackup.Controls.Add(this.checkBoxFullLoad);
this.groupBoxSaveBackup.Controls.Add(this.buttonSelectFolder); this.groupBoxSaveBackup.Controls.Add(this.buttonSaveSelectFolder);
this.groupBoxSaveBackup.Controls.Add(this.textBoxFolderName); this.groupBoxSaveBackup.Controls.Add(this.textBoxSaveFolderName);
this.groupBoxSaveBackup.Controls.Add(this.labelFolderName); this.groupBoxSaveBackup.Controls.Add(this.labelSaveFolderName);
this.groupBoxSaveBackup.Location = new System.Drawing.Point(0, 28); this.groupBoxSaveBackup.Location = new System.Drawing.Point(0, 28);
this.groupBoxSaveBackup.Name = "groupBoxSaveBackup"; this.groupBoxSaveBackup.Name = "groupBoxSaveBackup";
this.groupBoxSaveBackup.Size = new System.Drawing.Size(496, 100); this.groupBoxSaveBackup.Size = new System.Drawing.Size(496, 100);
@ -87,31 +96,31 @@ namespace SecurityWindowsDesktop.SpecialControls
this.checkBoxFullLoad.Text = "Полная выгрузка"; this.checkBoxFullLoad.Text = "Полная выгрузка";
this.checkBoxFullLoad.UseVisualStyleBackColor = true; this.checkBoxFullLoad.UseVisualStyleBackColor = true;
// //
// buttonSelectFolder // buttonSaveSelectFolder
// //
this.buttonSelectFolder.Location = new System.Drawing.Point(385, 26); this.buttonSaveSelectFolder.Location = new System.Drawing.Point(385, 26);
this.buttonSelectFolder.Name = "buttonSelectFolder"; this.buttonSaveSelectFolder.Name = "buttonSaveSelectFolder";
this.buttonSelectFolder.Size = new System.Drawing.Size(99, 23); this.buttonSaveSelectFolder.Size = new System.Drawing.Size(99, 23);
this.buttonSelectFolder.TabIndex = 2; this.buttonSaveSelectFolder.TabIndex = 2;
this.buttonSelectFolder.Text = "Выбрать папку"; this.buttonSaveSelectFolder.Text = "Выбрать папку";
this.buttonSelectFolder.UseVisualStyleBackColor = true; this.buttonSaveSelectFolder.UseVisualStyleBackColor = true;
this.buttonSelectFolder.Click += new System.EventHandler(this.ButtonSelectFolder_Click); this.buttonSaveSelectFolder.Click += new System.EventHandler(this.ButtonSaveSelectFolder_Click);
// //
// textBoxFolderName // textBoxSaveFolderName
// //
this.textBoxFolderName.Location = new System.Drawing.Point(107, 26); this.textBoxSaveFolderName.Location = new System.Drawing.Point(110, 26);
this.textBoxFolderName.Name = "textBoxFolderName"; this.textBoxSaveFolderName.Name = "textBoxSaveFolderName";
this.textBoxFolderName.Size = new System.Drawing.Size(272, 23); this.textBoxSaveFolderName.Size = new System.Drawing.Size(269, 23);
this.textBoxFolderName.TabIndex = 1; this.textBoxSaveFolderName.TabIndex = 1;
// //
// labelFolderName // labelSaveFolderName
// //
this.labelFolderName.AutoSize = true; this.labelSaveFolderName.AutoSize = true;
this.labelFolderName.Location = new System.Drawing.Point(16, 29); this.labelSaveFolderName.Location = new System.Drawing.Point(16, 29);
this.labelFolderName.Name = "labelFolderName"; this.labelSaveFolderName.Name = "labelSaveFolderName";
this.labelFolderName.Size = new System.Drawing.Size(85, 15); this.labelSaveFolderName.Size = new System.Drawing.Size(85, 15);
this.labelFolderName.TabIndex = 0; this.labelSaveFolderName.TabIndex = 0;
this.labelFolderName.Text = "Путь до папки"; this.labelSaveFolderName.Text = "Путь до папки";
// //
// toolStripHeader // toolStripHeader
// //
@ -134,10 +143,89 @@ namespace SecurityWindowsDesktop.SpecialControls
this.toolStripButtonClose.Size = new System.Drawing.Size(23, 22); this.toolStripButtonClose.Size = new System.Drawing.Size(23, 22);
this.toolStripButtonClose.Text = "Закрыть"; this.toolStripButtonClose.Text = "Закрыть";
// //
// groupBoxLoadBackup
//
this.groupBoxLoadBackup.Controls.Add(this.buttonRestoreBackup);
this.groupBoxLoadBackup.Controls.Add(this.buttonLoadArchiveSelect);
this.groupBoxLoadBackup.Controls.Add(this.textBoxLoadArchiveName);
this.groupBoxLoadBackup.Controls.Add(this.labelLoadArchiveName);
this.groupBoxLoadBackup.Controls.Add(this.buttonLoadSelectFolder);
this.groupBoxLoadBackup.Controls.Add(this.textBoxLoadFolderName);
this.groupBoxLoadBackup.Controls.Add(this.labelLoadFolderName);
this.groupBoxLoadBackup.Location = new System.Drawing.Point(0, 134);
this.groupBoxLoadBackup.Name = "groupBoxLoadBackup";
this.groupBoxLoadBackup.Size = new System.Drawing.Size(496, 137);
this.groupBoxLoadBackup.TabIndex = 2;
this.groupBoxLoadBackup.TabStop = false;
this.groupBoxLoadBackup.Text = "Загрузка из бекапа";
//
// buttonRestoreBackup
//
this.buttonRestoreBackup.Location = new System.Drawing.Point(383, 99);
this.buttonRestoreBackup.Name = "buttonRestoreBackup";
this.buttonRestoreBackup.Size = new System.Drawing.Size(99, 23);
this.buttonRestoreBackup.TabIndex = 9;
this.buttonRestoreBackup.Text = "Загрузить";
this.buttonRestoreBackup.UseVisualStyleBackColor = true;
this.buttonRestoreBackup.Click += new System.EventHandler(this.ButtonRestoreBackup_Click);
//
// buttonLoadArchiveSelect
//
this.buttonLoadArchiveSelect.Location = new System.Drawing.Point(383, 64);
this.buttonLoadArchiveSelect.Name = "buttonLoadArchiveSelect";
this.buttonLoadArchiveSelect.Size = new System.Drawing.Size(99, 23);
this.buttonLoadArchiveSelect.TabIndex = 8;
this.buttonLoadArchiveSelect.Text = "Выбрать файл";
this.buttonLoadArchiveSelect.UseVisualStyleBackColor = true;
this.buttonLoadArchiveSelect.Click += new System.EventHandler(this.ButtonLoadArchiveSelect_Click);
//
// textBoxLoadArchiveName
//
this.textBoxLoadArchiveName.Location = new System.Drawing.Point(110, 64);
this.textBoxLoadArchiveName.Name = "textBoxLoadArchiveName";
this.textBoxLoadArchiveName.Size = new System.Drawing.Size(267, 23);
this.textBoxLoadArchiveName.TabIndex = 7;
//
// labelLoadArchiveName
//
this.labelLoadArchiveName.AutoSize = true;
this.labelLoadArchiveName.Location = new System.Drawing.Point(14, 67);
this.labelLoadArchiveName.Name = "labelLoadArchiveName";
this.labelLoadArchiveName.Size = new System.Drawing.Size(90, 15);
this.labelLoadArchiveName.TabIndex = 6;
this.labelLoadArchiveName.Text = "Путь до архива";
//
// buttonLoadSelectFolder
//
this.buttonLoadSelectFolder.Location = new System.Drawing.Point(385, 28);
this.buttonLoadSelectFolder.Name = "buttonLoadSelectFolder";
this.buttonLoadSelectFolder.Size = new System.Drawing.Size(99, 23);
this.buttonLoadSelectFolder.TabIndex = 5;
this.buttonLoadSelectFolder.Text = "Выбрать папку";
this.buttonLoadSelectFolder.UseVisualStyleBackColor = true;
this.buttonLoadSelectFolder.Click += new System.EventHandler(this.ButtonLoadSelectFolder_Click);
//
// textBoxLoadFolderName
//
this.textBoxLoadFolderName.Location = new System.Drawing.Point(110, 28);
this.textBoxLoadFolderName.Name = "textBoxLoadFolderName";
this.textBoxLoadFolderName.Size = new System.Drawing.Size(269, 23);
this.textBoxLoadFolderName.TabIndex = 4;
//
// labelLoadFolderName
//
this.labelLoadFolderName.AutoSize = true;
this.labelLoadFolderName.Location = new System.Drawing.Point(16, 31);
this.labelLoadFolderName.Name = "labelLoadFolderName";
this.labelLoadFolderName.Size = new System.Drawing.Size(85, 15);
this.labelLoadFolderName.TabIndex = 3;
this.labelLoadFolderName.Text = "Путь до папки";
//
// BackupControl // BackupControl
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.groupBoxLoadBackup);
this.Controls.Add(this.toolStripHeader); this.Controls.Add(this.toolStripHeader);
this.Controls.Add(this.groupBoxSaveBackup); this.Controls.Add(this.groupBoxSaveBackup);
this.Name = "BackupControl"; this.Name = "BackupControl";
@ -146,6 +234,8 @@ namespace SecurityWindowsDesktop.SpecialControls
this.groupBoxSaveBackup.PerformLayout(); this.groupBoxSaveBackup.PerformLayout();
this.toolStripHeader.ResumeLayout(false); this.toolStripHeader.ResumeLayout(false);
this.toolStripHeader.PerformLayout(); this.toolStripHeader.PerformLayout();
this.groupBoxLoadBackup.ResumeLayout(false);
this.groupBoxLoadBackup.PerformLayout();
this.ResumeLayout(false); this.ResumeLayout(false);
this.PerformLayout(); this.PerformLayout();
@ -154,13 +244,21 @@ namespace SecurityWindowsDesktop.SpecialControls
#endregion #endregion
private System.Windows.Forms.GroupBox groupBoxSaveBackup; private System.Windows.Forms.GroupBox groupBoxSaveBackup;
private System.Windows.Forms.Label labelFolderName; private System.Windows.Forms.Label labelSaveFolderName;
private System.Windows.Forms.TextBox textBoxFolderName; private System.Windows.Forms.TextBox textBoxSaveFolderName;
private System.Windows.Forms.Button buttonSelectFolder; private System.Windows.Forms.Button buttonSaveSelectFolder;
private System.Windows.Forms.CheckBox checkBoxCreateArchive; private System.Windows.Forms.CheckBox checkBoxCreateArchive;
private System.Windows.Forms.Button buttonCreateBackup; private System.Windows.Forms.Button buttonCreateBackup;
private System.Windows.Forms.CheckBox checkBoxFullLoad; private System.Windows.Forms.CheckBox checkBoxFullLoad;
private System.Windows.Forms.ToolStrip toolStripHeader; private System.Windows.Forms.ToolStrip toolStripHeader;
private System.Windows.Forms.ToolStripButton toolStripButtonClose; private System.Windows.Forms.ToolStripButton toolStripButtonClose;
private System.Windows.Forms.GroupBox groupBoxLoadBackup;
private System.Windows.Forms.TextBox textBoxLoadFolderName;
private System.Windows.Forms.Label labelLoadFolderName;
private System.Windows.Forms.Button buttonLoadSelectFolder;
private System.Windows.Forms.Label labelLoadArchiveName;
private System.Windows.Forms.TextBox textBoxLoadArchiveName;
private System.Windows.Forms.Button buttonLoadArchiveSelect;
private System.Windows.Forms.Button buttonRestoreBackup;
} }
} }

View File

@ -7,11 +7,18 @@ using SecurityBusinessLogic.BindingModels;
using SecurityBusinessLogic.BusinessLogics; using SecurityBusinessLogic.BusinessLogics;
using System; using System;
using System.Windows.Forms; using System.Windows.Forms;
using System.Xml.Linq;
namespace SecurityWindowsDesktop.SpecialControls namespace SecurityWindowsDesktop.SpecialControls
{ {
/// <summary>
/// Контрол для работы с бекапом
/// </summary>
public partial class BackupControl : UserControl, IControl public partial class BackupControl : UserControl, IControl
{ {
/// <summary>
/// Класс с бизнес-лоникой работы с бекапом
/// </summary>
private readonly BackupBusinessLogic _businessLogic; private readonly BackupBusinessLogic _businessLogic;
/// <summary> /// <summary>
@ -19,6 +26,9 @@ namespace SecurityWindowsDesktop.SpecialControls
/// </summary> /// </summary>
private event Action<Guid> CloseEvent; private event Action<Guid> CloseEvent;
/// <summary>
/// Контрол для работы с бекапом
/// </summary>
public BackupControl() public BackupControl()
{ {
InitializeComponent(); InitializeComponent();
@ -28,6 +38,7 @@ namespace SecurityWindowsDesktop.SpecialControls
AccessOperation = AccessOperation.РаботасБекапом; AccessOperation = AccessOperation.РаботасБекапом;
} }
#region IControl
public Guid ControlId { get; private set; } public Guid ControlId { get; private set; }
public string Title { get; private set; } public string Title { get; private set; }
@ -36,10 +47,6 @@ namespace SecurityWindowsDesktop.SpecialControls
public IControl GetInstance() => new BackupControl() { ControlId = Guid.NewGuid() }; public IControl GetInstance() => new BackupControl() { ControlId = Guid.NewGuid() };
public void LoadFromXml(string xml)
{
}
public void Open(ControlOpenModel model) public void Open(ControlOpenModel model)
{ {
if (model.CloseList != null) if (model.CloseList != null)
@ -49,25 +56,58 @@ namespace SecurityWindowsDesktop.SpecialControls
Dock = DockStyle.Fill; Dock = DockStyle.Fill;
} }
public string SaveToXml() public string SaveToXml() => new XElement("Control",
new XAttribute("Type", GetType().FullName),
new XAttribute("ControlId", ControlId),
new XAttribute("Title", Title),
new XAttribute("AccessOperation", AccessOperation)).ToString();
public void LoadFromXml(string xml)
{ {
return string.Empty; var control = XElement.Parse(xml);
ControlId = new Guid(control.Attribute("ControlId").Value.ToString());
Title = control.Attribute("Title").Value.ToString();
AccessOperation = (AccessOperation)Enum.Parse(typeof(AccessOperation), control.Attribute("AccessOperation").Value.ToString());
}
#endregion
/// <summary>
/// Закрытие контрола
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ToolStripHeader_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
CloseEvent?.Invoke(ControlId);
Dispose();
} }
private void ButtonSelectFolder_Click(object sender, EventArgs e) /// <summary>
/// Выбор пути для папки сохранения бекапа
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSaveSelectFolder_Click(object sender, EventArgs e)
{ {
var fbd = new FolderBrowserDialog(); var fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK) if (fbd.ShowDialog() == DialogResult.OK)
{ {
textBoxFolderName.Text = fbd.SelectedPath; textBoxSaveFolderName.Text = fbd.SelectedPath;
} }
} }
/// <summary>
/// Создание бекапа
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateBackup_Click(object sender, EventArgs e) private void ButtonCreateBackup_Click(object sender, EventArgs e)
{ {
var cursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
if (_businessLogic.CreateBackUp(new BackupBindingModel if (_businessLogic.CreateBackUp(new BackupBindingModel
{ {
FolderName = textBoxFolderName.Text, FolderName = textBoxSaveFolderName.Text,
FullData = checkBoxFullLoad.Checked, FullData = checkBoxFullLoad.Checked,
CreateArchive = checkBoxCreateArchive.Checked CreateArchive = checkBoxCreateArchive.Checked
})) }))
@ -78,12 +118,59 @@ namespace SecurityWindowsDesktop.SpecialControls
{ {
DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при сохранении"); DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при сохранении");
} }
Cursor.Current = cursor;
} }
private void ToolStripHeader_ItemClicked(object sender, ToolStripItemClickedEventArgs e) /// <summary>
/// Выбор пути для папки восстановления бекапа
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonLoadSelectFolder_Click(object sender, EventArgs e)
{ {
CloseEvent?.Invoke(ControlId); var fbd = new FolderBrowserDialog();
Dispose(); if (fbd.ShowDialog() == DialogResult.OK)
{
textBoxLoadFolderName.Text = fbd.SelectedPath;
}
}
/// <summary>
/// Выбор пути для файла-архива с бекапом
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonLoadArchiveSelect_Click(object sender, EventArgs e)
{
var ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
textBoxLoadArchiveName.Text = ofd.FileName;
}
}
/// <summary>
/// Восстановление
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRestoreBackup_Click(object sender, EventArgs e)
{
var cursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
if (_businessLogic.RestoreBackUp(new BackupBindingModel
{
FolderName = textBoxLoadFolderName.Text,
ArchiveFileName = textBoxLoadArchiveName.Text
}))
{
DialogHelper.MessageInformation("Сохранение прошло успешно", "Результат");
}
else
{
DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при сохранении");
}
Cursor.Current = cursor;
} }
} }
} }