выгрузка в бекап

This commit is contained in:
kotcheshir73 2021-04-02 15:53:15 +04:00
parent 680823a981
commit 11c8de59e8
56 changed files with 874 additions and 39 deletions

View File

@ -1,5 +1,6 @@
using ModuleTools.Attributes;
using ModuleTools.Enums;
using ModuleTools.Interfaces;
using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
@ -12,7 +13,7 @@ namespace DatabaseCore.Models.Security
[DataContract]
[EntityDescription("Access", "Доступные действия для ролей")]
[EntityDependency("Role", "RoleId", "Доступные дейсвтиия создаются под конкретную роль")]
public class Access : BaseEntity
public class Access : BaseEntity, IEntitySecurityExtenstion<Access>
{
[Required]
[DataMember]
@ -33,6 +34,15 @@ namespace DatabaseCore.Models.Security
public virtual Role Role { get; set; }
public Access SecurityCheck(Access entity, bool allowFullData)
{
if (!allowFullData)
{
entity.AccessType = AccessType.View;
}
return entity;
}
//-------------------------------------------------------------------------
}
}

View File

@ -1,4 +1,5 @@
using ModuleTools.Attributes;
using ModuleTools.Interfaces;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
@ -9,7 +10,7 @@ namespace DatabaseCore.Models.Security
/// </summary>
[DataContract]
[EntityDescription("EnviromentSetting", "Общие настройки системы")]
public class EnviromentSetting : IdEntity
public class EnviromentSetting : IdEntity, IEntitySecurityExtenstion<EnviromentSetting>
{
[DataMember]
[MapConfiguration("Key")]
@ -24,5 +25,14 @@ namespace DatabaseCore.Models.Security
[DataMember]
[MapConfiguration("Description")]
public string Description { get; set; }
public EnviromentSetting SecurityCheck(EnviromentSetting entity, bool allowFullData)
{
if (!allowFullData)
{
entity.Value = "скрыто";
}
return entity;
}
}
}

View File

@ -1,4 +1,5 @@
using ModuleTools.Attributes;
using ModuleTools.Interfaces;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
@ -10,7 +11,7 @@ namespace DatabaseCore.Models.Security
/// </summary>
[DataContract]
[EntityDescription("Role", "Роли в системе")]
public class Role : BaseEntity
public class Role : BaseEntity, IEntitySecurityExtenstion<Role>
{
[DataMember]
[MapConfiguration("RoleName")]
@ -29,5 +30,8 @@ namespace DatabaseCore.Models.Security
[ForeignKey("RoleId")]
public virtual List<UserRole> UserRoles { get; set; }
public Role SecurityCheck(Role entity, bool allowFullData) => entity;
}
}

View File

@ -1,4 +1,5 @@
using ModuleTools.Attributes;
using ModuleTools.Interfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
@ -11,7 +12,7 @@ namespace DatabaseCore.Models.Security
/// </summary>
[DataContract]
[EntityDescription("User", "Пользователи системы")]
public class User : BaseEntity
public class User : BaseEntity, IEntitySecurityExtenstion<User>
{
[DataMember]
[MapConfiguration("Login")]
@ -47,5 +48,20 @@ namespace DatabaseCore.Models.Security
[ForeignKey("UserId")]
public virtual List<UserRole> UserRoles { get; set; }
public User SecurityCheck(User entity, bool allowFullData)
{
if (!allowFullData)
{
entity.PasswordHash = SecurityManager.GetPasswordHash("qwerty");
entity.Avatar = null;
entity.IsBanned = false;
entity.DateBanned = null;
entity.CountAttempt = 0;
entity.DateLastVisit = null;
}
return entity;
}
}
}

View File

@ -1,4 +1,5 @@
using ModuleTools.Attributes;
using ModuleTools.Interfaces;
using System;
using System.Runtime.Serialization;
@ -11,7 +12,7 @@ namespace DatabaseCore.Models.Security
[EntityDescription("UserRole", "Связь пользователей системы с ролями, которые им назначены")]
[EntityDependency("Role", "RoleId", "К какой роли относится пользователь")]
[EntityDependency("User", "UserId", "К какой роли относится пользователь")]
public class UserRole : BaseEntity
public class UserRole : BaseEntity, IEntitySecurityExtenstion<UserRole>
{
[DataMember]
[MapConfiguration("RoleId")]
@ -27,6 +28,8 @@ namespace DatabaseCore.Models.Security
public virtual User User { get; set; }
public UserRole SecurityCheck(UserRole entity, bool allowFullData) => entity;
//-------------------------------------------------------------------------
}
}

View File

@ -188,7 +188,7 @@ namespace DatabaseCore
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
private static string GetPasswordHash(string password) => Encoding.ASCII.GetString((new MD5CryptoServiceProvider()).ComputeHash(Encoding.ASCII.GetBytes(password)));
public static string GetPasswordHash(string password) => Encoding.ASCII.GetString((new MD5CryptoServiceProvider()).ComputeHash(Encoding.ASCII.GetBytes(password)));
/// <summary>
/// Проверка пользователя при авторизации и при смене пароля

View File

@ -9,9 +9,15 @@ namespace DesktopTools.Interfaces
public interface IWindowDesktopExtension
{
/// <summary>
/// Получение списка контролов модуля, доступных для работы по авторизованному пользователю
/// Получение списка контролов модуля для работсы с сущностями, доступных для работы по авторизованному пользователю
/// </summary>
/// <returns></returns>
List<WindowDesktopExtensionControlModel> GetListControlEntityList();
/// <summary>
/// Получение списка контролов модуля для особой работы, доступных для работы по авторизованному пользователю
/// </summary>
/// <returns></returns>
List<WindowDesktopExtensionControlModel> GetListControlSpecialList();
}
}

View File

@ -17,6 +17,8 @@
НастройкиСреды = 4,
ПользователиРоли = 5,
РаботасБекапом = 10,
#endregion
#region База

View File

@ -0,0 +1,18 @@
namespace ModuleTools.Interfaces
{
/// <summary>
/// Работа с сущностями с применением скрытности для полей
/// </summary>
/// <typeparam name="T">Сущность</typeparam>
public interface IEntitySecurityExtenstion<T>
where T: new()
{
/// <summary>
/// Обработка сущности для сокрытия важных полей
/// </summary>
/// <param name="entity"></param>
/// <param name="allowFullData"></param>
/// <returns></returns>
T SecurityCheck(T entity, bool allowFullData);
}
}

View File

@ -28,10 +28,11 @@ namespace DepartmentPortalDesctop
var extensions = DesktopLoader.GetWindowDesktopExtensions();
foreach (var extens in extensions)
{
ToolStripMenuItem menu = null;
var list = extens?.GetListControlEntityList()?.ToList();
if (list != null && list.Count > 0)
{
var menu = new ToolStripMenuItem { Text = list[0].Title };
menu = new ToolStripMenuItem { Text = list[0].Title };
for (int i = 0; i < list.Count; i++)
{
if (list[i].Control is IControl control)
@ -51,17 +52,54 @@ namespace DepartmentPortalDesctop
}
}
}
list = extens?.GetListControlSpecialList()?.ToList();
if (list != null && list.Count > 0)
{
if (menu == null)
{
menu = new ToolStripMenuItem { Text = list[0].Title };
}
else if (menu.Text != list[0].Title)
{
menuMain.Items.Add(menu);
menu = new ToolStripMenuItem { Text = list[0].Title };
}
menu.DropDownItems.Add(new ToolStripSeparator());
for (int i = 0; i < list.Count; i++)
{
if (list[i].Control is IControl control)
{
if (_baseControls.ContainsKey(list[i].Id))
{
continue;
}
_baseControls.Add(list[i].Id, control);
var submenu = new ToolStripMenuItem { Text = list[i].Title, Tag = list[i].Id };
submenu.Click += (object sender, EventArgs e) =>
{
OpenControl(new Guid((sender as ToolStripMenuItem).Tag.ToString()));
};
menu.DropDownItems.Add(submenu);
}
}
}
if (menu != null)
{
menuMain.Items.Add(menu);
}
}
if(File.Exists(_fileForXmlConfig))
if (File.Exists(_fileForXmlConfig))
{
var xml = XDocument.Load(_fileForXmlConfig).Element("Controls");
Guid? id = null;
if (xml != null)
{
foreach(XElement node in xml.Elements("Control"))
foreach (XElement node in xml.Elements("Control"))
{
var type = node.Attribute("Type").Value.ToString();
var control = _baseControls.Values.FirstOrDefault(x => x.GetType().FullName == type);
@ -177,7 +215,7 @@ namespace DepartmentPortalDesctop
private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
var xml = new XElement("Controls");
foreach(var cntrl in _controls)
foreach (var cntrl in _controls)
{
xml.AddFirst(XElement.Parse(cntrl.Value.SaveToXml()));
}

View File

@ -0,0 +1,23 @@
namespace SecurityBusinessLogic.BindingModels
{
/// <summary>
/// Информация по выгрузки/загрузки данных
/// </summary>
public class BackupBindingModel
{
/// <summary>
/// Путь до папки, куда выгружать бекап
/// </summary>
public string FolderName { get; set; }
/// <summary>
/// Выгрузка всех данных, либо только общедоступных
/// </summary>
public bool FullData { get; set; }
/// <summary>
/// Создать архив с выгрузкой
/// </summary>
public bool CreateArchive { get; set; }
}
}

View File

@ -0,0 +1,68 @@
using ModuleTools.BusinessLogics;
using ModuleTools.Enums;
using ModuleTools.Interfaces;
using ModuleTools.Models;
using SecurityBusinessLogic.BindingModels;
using SecurityBusinessLogic.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SecurityBusinessLogic.BusinessLogics
{
/// <summary>
/// Логика работы с бекапом
/// </summary>
public class BackupBusinessLogic
{
private IBackupService _service;
/// <summary>
/// Менеджер безопасности
/// </summary>
private ISecurityManager _security;
/// <summary>
/// Перечень ошибок при выполнении операции
/// </summary>
public List<(string Title, string Message)> Errors { get; protected set; }
public BackupBusinessLogic(IBackupService service)
{
_service = service;
_security = DependencyManager.Instance.Resolve<ISecurityManager>();
Errors = new();
}
public bool CreateBackUp(BackupBindingModel model)
{
if (NoAccess())
{
return false;
}
var result = _service.CreateBackUp(model);
if (!result.IsSucceeded)
{
Errors.AddRange(result.Errors);
return false;
}
return true;
}
/// <summary>
/// Проверка доступности операции для пользователя
/// </summary>
/// <returns></returns>
private bool NoAccess()
{
if (_security.CheckAccess(new SecurityManagerCheckAccessModel(null, AccessOperation.РаботасБекапом, AccessType.View, "бекап")))
{
return false;
}
Errors.Add(("Ошибка безопасности", _security.ErrorMessage));
return true;
}
}
}

View File

@ -0,0 +1,13 @@
using ModuleTools.Models;
using SecurityBusinessLogic.BindingModels;
namespace SecurityBusinessLogic.Interfaces
{
/// <summary>
/// Сервис работы по выгрузке и загрузке данных
/// </summary>
public interface IBackupService
{
OperationResultModel CreateBackUp(BackupBindingModel model);
}
}

View File

@ -0,0 +1,54 @@
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

@ -14,6 +14,8 @@ namespace SecurityDatabaseImplementation
DependencyManager.Instance.RegisterType<IRoleService, RoleService>();
DependencyManager.Instance.RegisterType<IUserService, UserService>();
DependencyManager.Instance.RegisterType<IUserRoleService, UserRoleService>();
DependencyManager.Instance.RegisterType<IBackupService, BackupService>();
}
}
}

View File

@ -1,5 +1,5 @@

namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
partial class ControlAccessElement
{

View File

@ -5,7 +5,7 @@ using SecurityBusinessLogic.BusinessLogics;
using SecurityBusinessLogic.ViewModels;
using System;
namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
public partial class ControlAccessElement :
GenericControlEntityElement<AccessGetBindingModel, AccessSetBindingModel, AccessListViewModel, AccessViewModel, AccessBusinessLogic>,

View File

@ -1,5 +1,5 @@

namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
partial class ControlAccessList
{

View File

@ -12,7 +12,7 @@ using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
/// <summary>
/// Реализация контрола для списка доступов

View File

@ -1,5 +1,5 @@

namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
partial class ControlEnviromentSettingElement
{

View File

@ -5,7 +5,7 @@ using SecurityBusinessLogic.BusinessLogics;
using SecurityBusinessLogic.ViewModels;
using System;
namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
public partial class ControlEnviromentSettingElement :
GenericControlEntityElement<EnviromentSettingGetBindingModel, EnviromentSettingSetBindingModel, EnviromentSettingListViewModel, EnviromentSettingViewModel, EnviromentSettingBusinessLogic>,

View File

@ -1,5 +1,5 @@

namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
partial class ControlEnviromentSettingList
{

View File

@ -9,7 +9,7 @@ using SecurityBusinessLogic.ViewModels;
using System;
using System.Collections.Generic;
namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
/// <summary>
/// Реализация контрола для списка настроек среды

View File

@ -1,5 +1,5 @@

namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
partial class ControlRoleElement
{

View File

@ -5,7 +5,7 @@ using SecurityBusinessLogic.BusinessLogics;
using SecurityBusinessLogic.ViewModels;
using System;
namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
public partial class ControlRoleElement :
GenericControlEntityElement<RoleGetBindingModel, RoleSetBindingModel, RoleListViewModel, RoleViewModel, RoleBusinessLogic>,

View File

@ -1,5 +1,5 @@

namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
partial class ControlRoleList
{

View File

@ -9,7 +9,7 @@ using SecurityBusinessLogic.ViewModels;
using System;
using System.Collections.Generic;
namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
/// <summary>
/// Реализация контрола для списка ролей

View File

@ -1,5 +1,5 @@

namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
partial class ControlRoleUserList
{

View File

@ -9,7 +9,7 @@ using SecurityBusinessLogic.ViewModels;
using System;
using System.Collections.Generic;
namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
/// <summary>
/// Реализация контрола для списка пользователей роли

View File

@ -1,5 +1,5 @@

namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
partial class ControlUserElement
{

View File

@ -5,7 +5,7 @@ using SecurityBusinessLogic.BusinessLogics;
using SecurityBusinessLogic.ViewModels;
using System;
namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
public partial class ControlUserElement :
GenericControlEntityElement<UserGetBindingModel, UserSetBindingModel, UserListViewModel, UserViewModel, UserBusinessLogic>,

View File

@ -1,5 +1,5 @@

namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
partial class ControlUserList
{

View File

@ -10,7 +10,7 @@ using System;
using System.Linq;
using System.Windows.Forms;
namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
/// <summary>
/// Реализация контрола для списка пользователей

View File

@ -1,5 +1,5 @@

namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
partial class ControlUserRoleElement
{

View File

@ -5,7 +5,7 @@ using SecurityBusinessLogic.BusinessLogics;
using SecurityBusinessLogic.ViewModels;
using System;
namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
public partial class ControlUserRoleElement :
GenericControlEntityElement<UserRoleGetBindingModel, UserRoleSetBindingModel, UserRoleListViewModel, UserRoleViewModel, UserRoleBusinessLogic>,

View File

@ -1,5 +1,5 @@

namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
partial class ControlUserRoleList
{

View File

@ -9,7 +9,7 @@ using SecurityBusinessLogic.ViewModels;
using System;
using System.Collections.Generic;
namespace SecurityWindowsDesktop.Controls
namespace SecurityWindowsDesktop.EntityControls
{
/// <summary>
/// Реализация контрола для списка ролей пользователя

View File

@ -0,0 +1,73 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SecurityWindowsDesktop.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SecurityWindowsDesktop.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Close {
get {
object obj = ResourceManager.GetObject("Close", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="Close" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Close.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

Binary file not shown.

After

Width:  |  Height:  |  Size: 412 B

View File

@ -5,7 +5,8 @@ using ModuleTools.BusinessLogics;
using ModuleTools.Enums;
using ModuleTools.Interfaces;
using ModuleTools.Models;
using SecurityWindowsDesktop.Controls;
using SecurityWindowsDesktop.EntityControls;
using SecurityWindowsDesktop.SpecialControls;
using System.Collections.Generic;
namespace SecurityWindowsDesktop
@ -54,5 +55,45 @@ namespace SecurityWindowsDesktop
return list;
}
public List<WindowDesktopExtensionControlModel> GetListControlSpecialList()
{
var manager = DependencyManager.Instance.Resolve<ISecurityManager>();
if (manager == null)
{
return null;
}
if (!manager.CheckAccess(new SecurityManagerCheckAccessModel(new AccessBindingModel { UserIdForAccess = manager.User },
AccessOperation.Администрирование, AccessType.View, "Администрирование")))
{
return null;
}
var list = new List<WindowDesktopExtensionControlModel>
{
new WindowDesktopExtensionControlModel { Title = "Администрирование" }
};
List<IControl> _controls = new()
{
new BackupControl()
};
foreach (var cntrl in _controls)
{
if (manager.CheckAccess(new SecurityManagerCheckAccessModel(new AccessBindingModel { UserIdForAccess = manager.User },
cntrl.AccessOperation, AccessType.View, cntrl.Title)))
{
list.Add(new WindowDesktopExtensionControlModel
{
Id = cntrl.ControlId,
Title = cntrl.Title,
Control = cntrl
});
}
}
return list;
}
}
}

View File

@ -14,6 +14,21 @@
<ProjectReference Include="..\SecurityBusinessLogic\SecurityBusinessLogic.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)$(ProjectName).dll&quot; &quot;$(SolutionDir)WindowDestopExtensions\$(ProjectName).dll&quot;" />
</Target>

View File

@ -0,0 +1,166 @@

namespace SecurityWindowsDesktop.SpecialControls
{
partial class BackupControl
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
this.groupBoxSaveBackup = new System.Windows.Forms.GroupBox();
this.buttonCreateBackup = new System.Windows.Forms.Button();
this.checkBoxCreateArchive = new System.Windows.Forms.CheckBox();
this.checkBoxFullLoad = new System.Windows.Forms.CheckBox();
this.buttonSelectFolder = new System.Windows.Forms.Button();
this.textBoxFolderName = new System.Windows.Forms.TextBox();
this.labelFolderName = new System.Windows.Forms.Label();
this.toolStripHeader = new System.Windows.Forms.ToolStrip();
this.toolStripButtonClose = new System.Windows.Forms.ToolStripButton();
this.groupBoxSaveBackup.SuspendLayout();
this.toolStripHeader.SuspendLayout();
this.SuspendLayout();
//
// groupBoxSaveBackup
//
this.groupBoxSaveBackup.Controls.Add(this.buttonCreateBackup);
this.groupBoxSaveBackup.Controls.Add(this.checkBoxCreateArchive);
this.groupBoxSaveBackup.Controls.Add(this.checkBoxFullLoad);
this.groupBoxSaveBackup.Controls.Add(this.buttonSelectFolder);
this.groupBoxSaveBackup.Controls.Add(this.textBoxFolderName);
this.groupBoxSaveBackup.Controls.Add(this.labelFolderName);
this.groupBoxSaveBackup.Location = new System.Drawing.Point(0, 28);
this.groupBoxSaveBackup.Name = "groupBoxSaveBackup";
this.groupBoxSaveBackup.Size = new System.Drawing.Size(496, 100);
this.groupBoxSaveBackup.TabIndex = 0;
this.groupBoxSaveBackup.TabStop = false;
this.groupBoxSaveBackup.Text = "Сохранение в бекап";
//
// buttonCreateBackup
//
this.buttonCreateBackup.Location = new System.Drawing.Point(385, 71);
this.buttonCreateBackup.Name = "buttonCreateBackup";
this.buttonCreateBackup.Size = new System.Drawing.Size(99, 23);
this.buttonCreateBackup.TabIndex = 5;
this.buttonCreateBackup.Text = "Выгрузить";
this.buttonCreateBackup.UseVisualStyleBackColor = true;
this.buttonCreateBackup.Click += new System.EventHandler(this.ButtonCreateBackup_Click);
//
// checkBoxCreateArchive
//
this.checkBoxCreateArchive.AutoSize = true;
this.checkBoxCreateArchive.Location = new System.Drawing.Point(262, 55);
this.checkBoxCreateArchive.Name = "checkBoxCreateArchive";
this.checkBoxCreateArchive.Size = new System.Drawing.Size(104, 19);
this.checkBoxCreateArchive.TabIndex = 4;
this.checkBoxCreateArchive.Text = "Создать архив";
this.checkBoxCreateArchive.UseVisualStyleBackColor = true;
//
// checkBoxFullLoad
//
this.checkBoxFullLoad.AutoSize = true;
this.checkBoxFullLoad.Location = new System.Drawing.Point(120, 55);
this.checkBoxFullLoad.Name = "checkBoxFullLoad";
this.checkBoxFullLoad.Size = new System.Drawing.Size(121, 19);
this.checkBoxFullLoad.TabIndex = 3;
this.checkBoxFullLoad.Text = "Полная выгрузка";
this.checkBoxFullLoad.UseVisualStyleBackColor = true;
//
// buttonSelectFolder
//
this.buttonSelectFolder.Location = new System.Drawing.Point(385, 26);
this.buttonSelectFolder.Name = "buttonSelectFolder";
this.buttonSelectFolder.Size = new System.Drawing.Size(99, 23);
this.buttonSelectFolder.TabIndex = 2;
this.buttonSelectFolder.Text = "Выбрать папку";
this.buttonSelectFolder.UseVisualStyleBackColor = true;
this.buttonSelectFolder.Click += new System.EventHandler(this.ButtonSelectFolder_Click);
//
// textBoxFolderName
//
this.textBoxFolderName.Location = new System.Drawing.Point(107, 26);
this.textBoxFolderName.Name = "textBoxFolderName";
this.textBoxFolderName.Size = new System.Drawing.Size(272, 23);
this.textBoxFolderName.TabIndex = 1;
//
// labelFolderName
//
this.labelFolderName.AutoSize = true;
this.labelFolderName.Location = new System.Drawing.Point(16, 29);
this.labelFolderName.Name = "labelFolderName";
this.labelFolderName.Size = new System.Drawing.Size(85, 15);
this.labelFolderName.TabIndex = 0;
this.labelFolderName.Text = "Путь до папки";
//
// toolStripHeader
//
this.toolStripHeader.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripButtonClose});
this.toolStripHeader.Location = new System.Drawing.Point(0, 0);
this.toolStripHeader.Name = "toolStripHeader";
this.toolStripHeader.Size = new System.Drawing.Size(708, 25);
this.toolStripHeader.TabIndex = 1;
this.toolStripHeader.Text = "toolStrip1";
this.toolStripHeader.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.ToolStripHeader_ItemClicked);
//
// toolStripButtonClose
//
this.toolStripButtonClose.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.toolStripButtonClose.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButtonClose.Image = global::SecurityWindowsDesktop.Properties.Resources.Close;
this.toolStripButtonClose.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButtonClose.Name = "toolStripButtonClose";
this.toolStripButtonClose.Size = new System.Drawing.Size(23, 22);
this.toolStripButtonClose.Text = "Закрыть";
//
// BackupControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.toolStripHeader);
this.Controls.Add(this.groupBoxSaveBackup);
this.Name = "BackupControl";
this.Size = new System.Drawing.Size(708, 486);
this.groupBoxSaveBackup.ResumeLayout(false);
this.groupBoxSaveBackup.PerformLayout();
this.toolStripHeader.ResumeLayout(false);
this.toolStripHeader.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox groupBoxSaveBackup;
private System.Windows.Forms.Label labelFolderName;
private System.Windows.Forms.TextBox textBoxFolderName;
private System.Windows.Forms.Button buttonSelectFolder;
private System.Windows.Forms.CheckBox checkBoxCreateArchive;
private System.Windows.Forms.Button buttonCreateBackup;
private System.Windows.Forms.CheckBox checkBoxFullLoad;
private System.Windows.Forms.ToolStrip toolStripHeader;
private System.Windows.Forms.ToolStripButton toolStripButtonClose;
}
}

View File

@ -0,0 +1,89 @@
using DesktopTools.Helpers;
using DesktopTools.Interfaces;
using DesktopTools.Models;
using ModuleTools.BusinessLogics;
using ModuleTools.Enums;
using SecurityBusinessLogic.BindingModels;
using SecurityBusinessLogic.BusinessLogics;
using System;
using System.Windows.Forms;
namespace SecurityWindowsDesktop.SpecialControls
{
public partial class BackupControl : UserControl, IControl
{
private readonly BackupBusinessLogic _businessLogic;
/// <summary>
/// Событие, вызываемое при закрытии контрола
/// </summary>
private event Action<Guid> CloseEvent;
public BackupControl()
{
InitializeComponent();
_businessLogic = DependencyManager.Instance.Resolve<BackupBusinessLogic>();
Title = "Работа с бекапом";
ControlId = new Guid("cc9844e6-5d92-4c89-b817-4c17ec382bc1");
AccessOperation = AccessOperation.РаботасБекапом;
}
public Guid ControlId { get; private set; }
public string Title { get; private set; }
public AccessOperation AccessOperation { get; private set; }
public IControl GetInstance() => new BackupControl() { ControlId = Guid.NewGuid() };
public void LoadFromXml(string xml)
{
}
public void Open(ControlOpenModel model)
{
if (model.CloseList != null)
{
CloseEvent += model.CloseList;
}
Dock = DockStyle.Fill;
}
public string SaveToXml()
{
return string.Empty;
}
private void ButtonSelectFolder_Click(object sender, EventArgs e)
{
var fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
textBoxFolderName.Text = fbd.SelectedPath;
}
}
private void ButtonCreateBackup_Click(object sender, EventArgs e)
{
if (_businessLogic.CreateBackUp(new BackupBindingModel
{
FolderName = textBoxFolderName.Text,
FullData = checkBoxFullLoad.Checked,
CreateArchive = checkBoxCreateArchive.Checked
}))
{
DialogHelper.MessageInformation("Сохранение прошло успешно", "Результат");
}
else
{
DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при сохранении");
}
}
private void ToolStripHeader_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
CloseEvent?.Invoke(ControlId);
Dispose();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>