5 Commits

90 changed files with 3015 additions and 221 deletions

2
.gitignore vendored
View File

@@ -3,7 +3,7 @@
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
ImplementationExtensions/
# User-specific files
*.rsuser
*.suo

View File

@@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
<PackageReference Include="MailKit" Version="4.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
<PackageReference Include="System.Text.Encoding" Version="4.3.0" />

View File

@@ -0,0 +1,103 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantDataModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantBusinessLogic.BusinessLogics
{
public class BackUpLogic : IBackUpLogic
{
private readonly ILogger _logger;
private readonly IBackUpInfo _backUpInfo;
public BackUpLogic(ILogger<BackUpLogic> logger, IBackUpInfo backUpInfo)
{
_logger = logger;
_backUpInfo = backUpInfo;
}
public void CreateBackUp(BackUpSaveBinidngModel model)
{
if (_backUpInfo == null)
{
return;
}
try
{
_logger.LogDebug("Clear folder");
// зачистка папки и удаление старого архива
var dirInfo = new DirectoryInfo(model.FolderName);
if (dirInfo.Exists)
{
foreach (var file in dirInfo.GetFiles())
{
file.Delete();
}
}
_logger.LogDebug("Delete archive");
string fileName = $"{model.FolderName}.zip";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
// берем метод для сохранения
_logger.LogDebug("Get assembly");
var typeIId = typeof(IId);
var assembly = typeIId.Assembly;
if (assembly == null)
{
throw new ArgumentNullException("Сборка не найдена", nameof(assembly));
}
var types = assembly.GetTypes();
var method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance);
_logger.LogDebug("Find {count} types", types.Length);
foreach (var type in types)
{
if (type.IsInterface && type.GetInterface(typeIId.Name) != null)
{
var modelType = _backUpInfo.GetTypeByModelInterface(type.Name);
if (modelType == null)
{
throw new InvalidOperationException($"Не найден класс-модель для {type.Name}");
}
_logger.LogDebug("Call SaveToFile method for {name} type", type.Name);
// вызываем метод на выполнение
method?.MakeGenericMethod(modelType).Invoke(this, new object[] { model.FolderName });
}
}
_logger.LogDebug("Create zip and remove folder");
// архивируем
ZipFile.CreateFromDirectory(model.FolderName, fileName);
// удаляем папку
dirInfo.Delete(true);
}
catch (Exception)
{
throw;
}
}
private void SaveToFile<T>(string folderName) where T : class, new()
{
var records = _backUpInfo.GetList<T>();
if (records == null)
{
_logger.LogWarning("{type} type get null list", typeof(T).Name);
return;
}
var jsonFormatter = new DataContractJsonSerializer(typeof(List<T>));
using var fs = new FileStream(string.Format("{0}/{1}.json", folderName, typeof(T).Name), FileMode.OpenOrCreate);
jsonFormatter.WriteObject(fs, records);
}
}
}

View File

@@ -8,6 +8,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace AutomobilePlantBusinessLogic.BusinessLogics
@@ -96,13 +97,23 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
{
throw new ArgumentNullException("Нет имени клиента", nameof(model.ClientFIO));
}
if (string.IsNullOrEmpty(model.Email))
string email = model.Email;
Regex regex = new Regex(@"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
Match match = regex.Match(email);
if (match.Success)
{
throw new ArgumentNullException("Нет почты клиента", nameof(model.Email));
throw new ArgumentNullException("Не верная почта клиента", nameof(model.Email));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password));
throw new ArgumentNullException("Не верный пароль клиента", nameof(model.Password));
}
string password = model.Password;
Regex regexPass = new Regex(@"^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$");
Match matchPass = regexPass.Match(password);
if (!matchPass.Success)
{
throw new ArgumentNullException("Не верный пароль клиента", nameof(model.Password));
}
_logger.LogInformation("Client. ClientName:{ClientName}. Id: { Id}", model.ClientFIO, model.Id);
var element = _clientStorage.GetElement(new ClientSearchModel

View File

@@ -0,0 +1,75 @@
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantContracts.ViewModel;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantBusinessLogic.BusinessLogics
{
public class MessageLogic : IMessageInfoLogic
{
private readonly ILogger _logger;
private readonly IMessageInfoStorage _messageStorage;
public MessageLogic(ILogger<CarLogic> logger, IMessageInfoStorage messageStorage)
{
_logger = logger;
_messageStorage = messageStorage;
}
public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model)
{
_logger.LogInformation("ReadList");
var list = model == null ? _messageStorage.GetFullList() : _messageStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool Create(MessageInfoBindingModel model)
{
CheckModel(model);
if (_messageStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
private void CheckModel(MessageInfoBindingModel model, bool withParams =
true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.MessageId))
{
throw new ArgumentNullException("Нет айди письма", nameof(model.MessageId));
}
if (string.IsNullOrEmpty(model.Body))
{
throw new ArgumentNullException("Нет тела письма", nameof(model.Body));
}
if (string.IsNullOrEmpty(model.SenderName))
{
throw new ArgumentNullException("Нет отправителя письма", nameof(model.SenderName));
}
}
}
}

View File

@@ -1,4 +1,5 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantBusinessLogic.MailWorker;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.StoragesContracts;
@@ -18,10 +19,14 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<ComponentLogic> logger, IOrderStorage orderStorage)
private readonly IClientStorage _clientStorage;
private readonly AbstractMailWorker _mailKitWorker;
public OrderLogic(ILogger<ComponentLogic> logger, IOrderStorage orderStorage, IClientStorage clientStorage, AbstractMailWorker abstractMailWorker)
{
_logger = logger;
_orderStorage = orderStorage;
_clientStorage = clientStorage;
_mailKitWorker = abstractMailWorker;
}
public bool CreateOrder(OrderBindingModel model)
@@ -35,14 +40,20 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
}
model.Status = OrderStatus.Принят;
var newOrder = _orderStorage.Insert(model);
if (_orderStorage.Insert(model) == null)
if (newOrder == null)
{
model.Status = OrderStatus.Неизвестен;
_logger.LogWarning("Insert operation failed");
return false;
}
_mailKitWorker.MailSendAsync(new MailSendInfoBindingModel
{
MailAddress = (_clientStorage.GetElement(new ClientSearchModel { Id = newOrder.ClientId})).Email,
Subject = $"Заказ номер",
Text = $"Ваш заказ успешно принят. Машина: {model.CarName} в количестве: {model.Count} выйдет на сумму: {model.Sum}"
});
return true;
}
@@ -89,6 +100,12 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
_logger.LogWarning("Update operation failed");
return false;
}
_mailKitWorker.MailSendAsync(new MailSendInfoBindingModel
{
MailAddress = (_clientStorage.GetElement(new ClientSearchModel { Id = model.ClientId })).Email,
Subject = $"Заказ номер {model.Id}",
Text = $"Ваш заказ переведен в статус {newStatus}"
});
return true;
}

View File

@@ -0,0 +1,97 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantBusinessLogic.MailWorker
{
public abstract class AbstractMailWorker
{
protected string _mailLogin = string.Empty;
protected string _mailPassword = string.Empty;
protected string _smtpClientHost = string.Empty;
protected int _smtpClientPort;
protected string _popHost = string.Empty;
protected int _popPort;
private readonly IMessageInfoLogic _messageInfoLogic;
private readonly ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> logger, IMessageInfoLogic messageInfoLogic)
{
_logger = logger;
_messageInfoLogic = messageInfoLogic;
}
public void MailConfig(MailConfigBindingModel config)
{
_mailLogin = config.MailLogin;
_mailPassword = config.MailPassword;
_smtpClientHost = config.SmtpClientHost;
_smtpClientPort = config.SmtpClientPort;
_popHost = config.PopHost;
_popPort = config.PopPort;
_logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort);
}
public async void MailSendAsync(MailSendInfoBindingModel info)
{
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
{
return;
}
if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0)
{
return;
}
if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text))
{
return;
}
_logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject);
await SendMailAsync(info);
}
public async void MailCheck()
{
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
{
return;
}
if (string.IsNullOrEmpty(_popHost) || _popPort == 0)
{
return;
}
if (_messageInfoLogic == null)
{
return;
}
var list = await ReceiveMailAsync();
_logger.LogDebug("Check Mail: {Count} new mails", list.Count);
foreach (var mail in list)
{
_messageInfoLogic.Create(mail);
}
}
protected abstract Task SendMailAsync(MailSendInfoBindingModel info);
protected abstract Task<List<MessageInfoBindingModel>> ReceiveMailAsync();
}
}

View File

@@ -0,0 +1,83 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using MailKit.Net.Pop3;
using MailKit.Security;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Net.Mail;
using System.Text;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantContracts.SearchModel;
namespace AutomobilePlantBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
private readonly IClientStorage _clientStorage;
public MailKitWorker(ILogger<MailKitWorker> logger, IMessageInfoLogic messageInfoLogic, IClientStorage clientStorage) : base(logger, messageInfoLogic) { _clientStorage = clientStorage; }
protected override async Task SendMailAsync(MailSendInfoBindingModel info)
{
using var objMailMessage = new MailMessage();
using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort);
try
{
objMailMessage.From = new MailAddress(_mailLogin);
objMailMessage.To.Add(new MailAddress(info.MailAddress));
objMailMessage.Subject = info.Subject;
objMailMessage.Body = info.Text;
objMailMessage.SubjectEncoding = Encoding.UTF8;
objMailMessage.BodyEncoding = Encoding.UTF8;
objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true;
objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword);
await Task.Run(() => objSmtpClient.Send(objMailMessage));
}
catch (Exception)
{
throw;
}
}
protected override async Task<List<MessageInfoBindingModel>> ReceiveMailAsync()
{
var list = new List<MessageInfoBindingModel>();
using var client = new Pop3Client();
await Task.Run(() =>
{
try
{
client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect);
client.Authenticate(_mailLogin, _mailPassword);
for (int i = 0; i < client.Count; i++)
{
var message = client.GetMessage(i);
foreach (var mail in message.From.Mailboxes)
{
list.Add(new MessageInfoBindingModel
{
DateDelivery = DateTime.SpecifyKind(message.Date.DateTime, DateTimeKind.Utc),
ClientId = _clientStorage.GetElement(new ClientSearchModel { Email = mail.Address }).Id,
MessageId = message.MessageId,
SenderName = mail.Address,
Subject = message.Subject,
Body = message.TextBody
}); ;
}
}
}
catch (AuthenticationException)
{ }
finally
{
client.Disconnect(true);
}
});
return list;
}
}
}

View File

@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantContracts.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
public string Title { get; private set; }
public bool Visible { get; private set; }
public int Width { get; private set; }
public GridViewAutoSize GridViewAutoSize { get; private set; }
public bool IsUseAutoSize { get; private set; }
public ColumnAttribute(string title = "", bool visible = true, int width = 0, GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false)
{
Title = title;
Visible = visible;
Width = width;
GridViewAutoSize = gridViewAutoSize;
IsUseAutoSize = isUseAutoSize;
}
}
}

View File

@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantContracts.Attributes
{
public enum GridViewAutoSize
{
NotSet = 0,
None = 1,
ColumnHeader = 2,
AllCellsExceptHeader = 4,
AllCells = 6,
DisplayedCellsExceptHeader = 8,
DisplayedCells = 10,
Fill = 16
}
}

View File

@@ -6,6 +6,12 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AbstractAutoDataModels\AutomobilePlantDataModels.csproj" />
</ItemGroup>

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantContracts.BindingModels
{
public class BackUpSaveBinidngModel
{
public string FolderName { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,17 @@
namespace AutomobilePlantContracts.BindingModels
{
public class MailConfigBindingModel
{
public string MailLogin { get; set; } = string.Empty;
public string MailPassword { get; set; } = string.Empty;
public string SmtpClientHost { get; set; } = string.Empty;
public int SmtpClientPort { get; set; }
public string PopHost { get; set; } = string.Empty;
public int PopPort { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
namespace AutomobilePlantContracts.BindingModels
{
public class MailSendInfoBindingModel
{
public string MailAddress { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,21 @@
using AutomobilePlantDataModels.Models;
namespace AutomobilePlantContracts.BindingModels
{
public class MessageInfoBindingModel : IMessageInfoModel
{
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; }
public string SenderName { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; }
public int Id { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
using AutomobilePlantContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantContracts.BusinessLogicsContracts
{
public interface IBackUpLogic
{
void CreateBackUp(BackUpSaveBinidngModel model);
}
}

View File

@@ -0,0 +1,13 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.ViewModel;
namespace AutomobilePlantContracts.BusinessLogicsContracts
{
public interface IMessageInfoLogic
{
List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model);
bool Create(MessageInfoBindingModel model);
}
}

View File

@@ -0,0 +1,67 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;
namespace AutomobilePlantContracts.DI
{
public class DependencyManager
{
private readonly IDependencyContainer _dependencyManager;
private static DependencyManager? _manager;
private static readonly object _locjObject = new();
private DependencyManager()
{
_dependencyManager = new UnityServiceContainer();
}
public static DependencyManager Instance { get { if (_manager == null) { lock (_locjObject) { _manager = new DependencyManager(); } } return _manager; } }
/// <summary>
/// Иницализация библиотек, в которых идут установки зависомстей
/// </summary>
public static void InitDependency()
{
var ext = ServiceProviderLoader.GetImplementationExtensions();
if (ext == null)
{
throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям");
}
// регистрируем зависимости
ext.RegisterServices();
}
/// <summary>
/// Регистрация логгера
/// </summary>
/// <param name="configure"></param>
public void AddLogging(Action<ILoggingBuilder> configure) => _dependencyManager.AddLogging(configure);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
public void RegisterType<T, U>(bool isSingle = false) where U : class, T where T : class => _dependencyManager.RegisterType<T, U>(isSingle);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
public void RegisterType<T>(bool isSingle = false) where T : class => _dependencyManager.RegisterType<T>(isSingle);
/// <summary>
/// Получение класса со всеми зависмостями
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T Resolve<T>() => _dependencyManager.Resolve<T>();
}
}

View File

@@ -0,0 +1,40 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantContracts.DI
{
public interface IDependencyContainer
{
/// <summary>
/// Регистрация логгера
/// </summary>
/// <param name="configure"></param>
void AddLogging(Action<ILoggingBuilder> configure);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
/// <param name="isSingle"></param>
void RegisterType<T, U>(bool isSingle) where U : class, T where T : class;
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="isSingle"></param>
void RegisterType<T>(bool isSingle) where T : class;
/// <summary>
/// Получение класса со всеми зависмостями
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
T Resolve<T>();
}
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantContracts.DI
{
public interface IImplementationExtension
{
public int Priority { get; }
/// <summary>
/// Регистрация сервисов
/// </summary>
public void RegisterServices();
}
}

View File

@@ -0,0 +1,62 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantContracts.DI
{
public class ServiceDependencyContainer : IDependencyContainer
{
private ServiceProvider? _serviceProvider;
private readonly ServiceCollection _serviceCollection;
public ServiceDependencyContainer()
{
_serviceCollection = new ServiceCollection();
}
public void AddLogging(Action<ILoggingBuilder> configure)
{
_serviceCollection.AddLogging(configure);
}
public void RegisterType<T, U>(bool isSingle) where U : class, T where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T, U>();
}
else
{
_serviceCollection.AddTransient<T, U>();
}
_serviceProvider = null;
}
public void RegisterType<T>(bool isSingle) where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T>();
}
else
{
_serviceCollection.AddTransient<T>();
}
_serviceProvider = null;
}
public T Resolve<T>()
{
if (_serviceProvider == null)
{
_serviceProvider = _serviceCollection.BuildServiceProvider();
}
return _serviceProvider.GetService<T>()!;
}
}
}

View File

@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantContracts.DI
{
public class ServiceProviderLoader
{
/// <summary>
/// Загрузка всех классов-реализаций IImplementationExtension
/// </summary>
/// <returns></returns>
public static IImplementationExtension? GetImplementationExtensions()
{
IImplementationExtension? source = null;
var files = Directory.GetFiles(TryGetImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories);
foreach (var file in files.Distinct())
{
Assembly asm = Assembly.LoadFrom(file);
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && typeof(IImplementationExtension).IsAssignableFrom(t))
{
if (source == null)
{
source = (IImplementationExtension)Activator.CreateInstance(t)!;
}
else
{
var newSource = (IImplementationExtension)Activator.CreateInstance(t)!;
if (newSource.Priority > source.Priority)
{
source = newSource;
}
}
}
}
}
return source;
}
private static string TryGetImplementationExtensionsFolder()
{
var directory = new DirectoryInfo(Directory.GetCurrentDirectory());
while (directory != null && !directory.GetDirectories("ImplementationExtensions", SearchOption.AllDirectories).Any(x => x.Name == "ImplementationExtensions"))
{
directory = directory.Parent;
}
return $"{directory?.FullName}\\ImplementationExtensions";
}
}
}

View File

@@ -0,0 +1,59 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;
using Unity.Microsoft.Logging;
namespace AutomobilePlantContracts.DI
{
public class UnityServiceContainer : IDependencyContainer
{
private UnityContainer? _unityContainer;
public UnityServiceContainer()
{
_unityContainer = new UnityContainer();
}
public void AddLogging(Action<ILoggingBuilder> configure)
{
_unityContainer.AddExtension(new LoggingExtension(LoggerFactory.Create(configure)));
}
public void RegisterType<T, U>(bool isSingle) where U : class, T where T : class
{
if (isSingle)
{
_unityContainer.RegisterSingleton<T, U>();
}
else
{
_unityContainer.RegisterType<T, U>();
}
}
public void RegisterType<T>(bool isSingle) where T : class
{
if (isSingle)
{
_unityContainer.RegisterSingleton<T>();
}
else
{
_unityContainer.RegisterType<T>();
}
}
public T Resolve<T>()
{
return _unityContainer.Resolve<T>()!;
}
}
}

View File

@@ -0,0 +1,9 @@
namespace AutomobilePlantContracts.SearchModel
{
public class MessageInfoSearchModel
{
public int? ClientId { get; set; }
public string? MessageId { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantContracts.StoragesContracts
{
public interface IBackUpInfo
{
List<T>? GetList<T>() where T : class, new();
Type? GetTypeByModelInterface(string modelInterfaceName);
}
}

View File

@@ -0,0 +1,17 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.ViewModel;
namespace AbstractShopContracts.StoragesContracts
{
public interface IMessageInfoStorage
{
List<MessageInfoViewModel> GetFullList();
List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model);
MessageInfoViewModel? GetElement(MessageInfoSearchModel model);
MessageInfoViewModel? Insert(MessageInfoBindingModel model);
}
}

View File

@@ -5,15 +5,19 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using AutomobilePlantContracts.Attributes;
namespace AutomobilePlantContracts.ViewModel
{
public class CarViewModel : ICarModel
{
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("Название изделия")]
[Column(title: "Название", width: 150)]
public string CarName { get; set; } = string.Empty;
[DisplayName("Цена")]
[Column(title: "Цена", width: 50)]
public double Price { get; set; }
[Column(visible: false)]
public Dictionary<int, (IComponentModel, int)> CarComponents
{
get;

View File

@@ -1,4 +1,5 @@
using AutomobilePlantDataModels.Models;
using AutomobilePlantContracts.Attributes;
using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -10,12 +11,13 @@ namespace AutomobilePlantContracts.ViewModel
{
public class ClientViewModel : IClientModel
{
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("ФИО клиента")]
[Column(title: "Имя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Логин (эл. почта)")]
[Column(title: "Логин (эл. почта)", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Email { get; set; } = string.Empty;
[DisplayName("Пароль")]
[Column(title: "Пароль", width: 150)]
public string Password { get; set; } = string.Empty;
}
}

View File

@@ -5,14 +5,17 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using AutomobilePlantContracts.Attributes;
namespace AutomobilePlantContracts.ViewModel
{
public class ComponentViewModel : IComponentModel
{
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("Название компонента")]
[Column(title: "Название", width: 150)]
public string ComponentName { get; set; } = string.Empty;
[DisplayName("Цена")]
[Column(title: "Цена", width: 150)]
public double Cost { get; set; }
}
}

View File

@@ -1,4 +1,5 @@
using AutomobilePlantDataModels.Models;
using AutomobilePlantContracts.Attributes;
using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -10,18 +11,19 @@ namespace AutomobilePlantContracts.ViewModel
{
public class ImplementerViewModel : IImplementerModel
{
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("ФИО исполнителя")]
[Column(title: "Имя", width: 150)]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Пароль")]
[Column(title: "Пароль", width: 150)]
public string Password { get; set; } = string.Empty;
[DisplayName("Стаж работы")]
[Column(title: "Стаж", width: 100)]
public int WorkExperience { get; set; }
[DisplayName("Квалификация")]
[Column(title: "Квалификация", width: 100)]
public int Qualification { get; set; }
}
}

View File

@@ -0,0 +1,28 @@
using AutomobilePlantContracts.Attributes;
using AutomobilePlantDataModels.Models;
using System.ComponentModel;
namespace AutomobilePlantContracts.ViewModel
{
public class MessageInfoViewModel : IMessageInfoModel
{
[Column(visible: false)]
public string MessageId { get; set; } = string.Empty;
[Column(visible: false)]
public int? ClientId { get; set; }
[Column(title: "Отправитель", width: 150)]
public string SenderName { get; set; } = string.Empty;
[Column(title: "Дата", width: 100)]
public DateTime DateDelivery { get; set; }
[Column(title: "Заголовок", width: 150)]
public string Subject { get; set; } = string.Empty;
[Column(title: "Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Body { get; set; } = string.Empty;
[Column(visible: false)]
public int Id { get; set; }
}
}

View File

@@ -6,31 +6,35 @@ using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using AutomobilePlantDataModels.Enums;
using AutomobilePlantContracts.Attributes;
namespace AutomobilePlantContracts.ViewModel
{
public class OrderViewModel : IOrderModel
{
[DisplayName("Номер")]
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("Клиент")]
[Column(title: "Клиент", width: 150)]
public string ClientName { get; set; } = string.Empty;
[Column(visible: false)]
public int ClientId { get; set; }
[Column(visible: false)]
public int? ImplementerId { get; set; }
[DisplayName("Исполнитель")]
[Column(title: "Исполнитель", width: 150)]
public string? ImplementerName { get; set; } = string.Empty;
[Column(visible: false)]
public int CarId { get; set; }
[DisplayName("Изделие")]
[Column(title: "Машина", width: 150)]
public string CarName { get; set; } = string.Empty;
[DisplayName("Количество")]
[Column(title: "Кол-во", width: 150)]
public int Count { get; set; }
[DisplayName("Сумма")]
[Column(title: "Сумма", width: 150)]
public double Sum { get; set; }
[DisplayName("Статус")]
[Column(title: "Статус", width: 150)]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")]
[Column(title: "Дата создания", width: 150)]
public DateTime DateCreate { get; set; } = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
[DisplayName("Дата выполнения")]
[Column(title: "Дата выполнения", width: 150)]
public DateTime? DateImplement { get; set; }
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantDataModels.Models
{
public interface IMessageInfoModel : IId
{
string MessageId { get; }
int? ClientId { get; }
string SenderName { get; }
DateTime DateDelivery { get; }
string Subject { get; }
string Body { get; }
}
}

View File

@@ -11,4 +11,8 @@
<ProjectReference Include="..\AbstractAutoDataModels\AutomobilePlantDataModels.csproj" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project>

View File

@@ -15,6 +15,7 @@ namespace AutomobilePlantListImplement
public List<Car> Cars { get; set; }
public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
public List<MessageInfoModel> Messages { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
@@ -22,6 +23,7 @@ namespace AutomobilePlantListImplement
Cars = new List<Car>();
Clients = new List<Client>();
Implementers = new List<Implementer>();
Messages = new List<MessageInfoModel>();
}
public static DataListSingleton GetInstance()
{

View File

@@ -0,0 +1,17 @@
using AutomobilePlantContracts.StoragesContracts;
namespace AutomobilePlantListImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
throw new NotImplementedException();
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
throw new NotImplementedException();
}
}
}

View File

@@ -0,0 +1,98 @@
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.ViewModel;
using AutomobilePlantListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantListImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
private readonly DataListSingleton _source;
public MessageInfoStorage()
{
_source = DataListSingleton.GetInstance();
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (string.IsNullOrEmpty(model.MessageId) )
{
return null;
}
foreach (var message in _source.Messages)
{
if (!string.IsNullOrEmpty(model.MessageId) && message.MessageId.Equals(model.MessageId) )
{
return message.GetViewModel;
}
}
return null;
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
var result = new List<MessageInfoViewModel>();
if (!model.ClientId.HasValue)
{
return result;
}
foreach (var message in _source.Messages)
{
if (message.ClientId == model.ClientId)
{
result.Add(message.GetViewModel);
}
}
return result;
}
public List<MessageInfoViewModel> GetFullList()
{
var result = new List<MessageInfoViewModel>();
foreach (var message in _source.Messages)
{
result.Add(message.GetViewModel);
}
return result;
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
model.MessageId = "1";
foreach (var message in _source.Messages)
{
if (model.MessageId.Equals(message.MessageId))
{
model.MessageId = (Convert.ToInt32(message.MessageId) +1).ToString();
}
}
var newMes = MessageInfoModel.Create(model);
if (newMes == null)
{
return null;
}
_source.Messages.Add(newMes);
return newMes.GetViewModel;
}
}
}

View File

@@ -0,0 +1,28 @@
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantContracts.DI;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantListImplement.Implements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantListImplement
{
public class ListImplementationExtension : IImplementationExtension
{
public int Priority => 0;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IComponentStorage, ComponentStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<ICarStorage, CarStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@@ -0,0 +1,57 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModel;
using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantListImplement.Models
{
public class MessageInfoModel : IMessageInfoModel
{
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; }
public string SenderName { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; }
public string Subject { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public static MessageInfoModel? Create(MessageInfoBindingModel? model)
{
if (model == null)
{
return null;
}
return new MessageInfoModel()
{
Id = model.Id,
MessageId = model.MessageId,
ClientId = model.ClientId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
Subject = model.Subject,
Body = model.Body,
};
}
public MessageInfoViewModel GetViewModel => new()
{
Id = Id,
MessageId = MessageId,
ClientId = ClientId,
SenderName = SenderName,
DateDelivery = DateDelivery,
Subject = Subject,
Body = Body,
};
public int Id { get; set; }
}
}

View File

@@ -147,5 +147,14 @@ namespace AutoPlantClientApp.Controllers
var prod = APIClient.GetRequest<CarViewModel>($"api/main/getcar?carId={car}");
return count * (prod?.Price ?? 1);
}
[HttpGet]
public IActionResult Mails()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<MessageInfoViewModel>>($"api/client/getmessages?ClientId={APIClient.Client.Id}"));
}
}
}

View File

@@ -0,0 +1,54 @@
@using AutomobilePlantContracts.ViewModel
@model List<MessageInfoViewModel>
@{
ViewData["Title"] = "Mails";
}
<div class="text-center">
<h1 class="display-4">Заказы</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<table class="table">
<thead>
<tr>
<th>
Дата письма
</th>
<th>
Заголовок
</th>
<th>
Текст
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.DateDelivery)
</td>
<td>
@Html.DisplayFor(modelItem => item.Subject)
</td>
<td>
@Html.DisplayFor(modelItem => item.Body)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@@ -29,6 +29,9 @@
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Mails">Письма</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Enter">Вход</a>
</li>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SmtpClientHost" value="smtp.gmail.com" />
<add key="SmtpClientPort" value="587" />
<add key="PopHost" value="pop.gmail.com" />
<add key="PopPort" value="995" />
<add key="MailLogin" value="labrpp89@gmail.com" />
<add key="MailPassword" value="swly dzcy ccaz vdvr" />
</appSettings>
</configuration>

View File

@@ -37,4 +37,10 @@
<ProjectReference Include="..\AutomobilePlantDataBaseImplements\AutomobilePlantDataBaseImplements.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="App.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,51 @@
using AutomobilePlantContracts.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlant
{
internal static class DataGridViewExtension
{
public static void FillAndConfigGrid<T>(this DataGridView grid, List<T>? data)
{
if (data == null)
{
return;
}
grid.DataSource = data;
var type = typeof(T);
var properties = type.GetProperties();
foreach (DataGridViewColumn column in grid.Columns)
{
var property = properties.FirstOrDefault(x => x.Name == column.Name);
if (property == null)
{
throw new InvalidOperationException($"В типе {type.Name} не найдено свойство с именем {column.Name}");
}
var attribute = property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault();
if (attribute == null)
{
throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства {property.Name}");
}
// ищем нужный нам атрибут
if (attribute is ColumnAttribute columnAttr)
{
column.HeaderText = columnAttr.Title;
column.Visible = columnAttr.Visible;
if (columnAttr.IsUseAutoSize)
{
column.AutoSizeMode = (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode), columnAttr.GridViewAutoSize.ToString());
}
else
{
column.Width = columnAttr.Width;
}
}
}
}
}
}

View File

@@ -53,33 +53,35 @@
// CarNameLabel
//
this.CarNameLabel.AutoSize = true;
this.CarNameLabel.Location = new System.Drawing.Point(12, 9);
this.CarNameLabel.Name = "PackageNameLabel";
this.CarNameLabel.Size = new System.Drawing.Size(65, 15);
this.CarNameLabel.Location = new System.Drawing.Point(14, 12);
this.CarNameLabel.Name = "CarNameLabel";
this.CarNameLabel.Size = new System.Drawing.Size(84, 20);
this.CarNameLabel.TabIndex = 0;
this.CarNameLabel.Text = "Название: ";
//
// PriceLabel
//
this.PriceLabel.AutoSize = true;
this.PriceLabel.Location = new System.Drawing.Point(12, 43);
this.PriceLabel.Location = new System.Drawing.Point(14, 57);
this.PriceLabel.Name = "PriceLabel";
this.PriceLabel.Size = new System.Drawing.Size(73, 15);
this.PriceLabel.Size = new System.Drawing.Size(90, 20);
this.PriceLabel.TabIndex = 1;
this.PriceLabel.Text = "Стоимость: ";
//
// CarNameTextBox
//
this.CarNameTextBox.Location = new System.Drawing.Point(83, 6);
this.CarNameTextBox.Name = "PackageNameTextBox";
this.CarNameTextBox.Size = new System.Drawing.Size(283, 23);
this.CarNameTextBox.Location = new System.Drawing.Point(95, 8);
this.CarNameTextBox.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.CarNameTextBox.Name = "CarNameTextBox";
this.CarNameTextBox.Size = new System.Drawing.Size(323, 27);
this.CarNameTextBox.TabIndex = 2;
//
// PriceTextBox
//
this.PriceTextBox.Location = new System.Drawing.Point(83, 40);
this.PriceTextBox.Location = new System.Drawing.Point(95, 53);
this.PriceTextBox.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.PriceTextBox.Name = "PriceTextBox";
this.PriceTextBox.Size = new System.Drawing.Size(283, 23);
this.PriceTextBox.Size = new System.Drawing.Size(323, 27);
this.PriceTextBox.TabIndex = 3;
//
// ComponentsGroupBox
@@ -89,18 +91,21 @@
this.ComponentsGroupBox.Controls.Add(this.ChangeButton);
this.ComponentsGroupBox.Controls.Add(this.AddButton);
this.ComponentsGroupBox.Controls.Add(this.DataGridView);
this.ComponentsGroupBox.Location = new System.Drawing.Point(12, 80);
this.ComponentsGroupBox.Location = new System.Drawing.Point(14, 107);
this.ComponentsGroupBox.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ComponentsGroupBox.Name = "ComponentsGroupBox";
this.ComponentsGroupBox.Size = new System.Drawing.Size(722, 350);
this.ComponentsGroupBox.Padding = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ComponentsGroupBox.Size = new System.Drawing.Size(825, 467);
this.ComponentsGroupBox.TabIndex = 5;
this.ComponentsGroupBox.TabStop = false;
this.ComponentsGroupBox.Text = "Компоненты";
//
// UpdateButton
//
this.UpdateButton.Location = new System.Drawing.Point(590, 203);
this.UpdateButton.Location = new System.Drawing.Point(674, 271);
this.UpdateButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.UpdateButton.Name = "UpdateButton";
this.UpdateButton.Size = new System.Drawing.Size(110, 38);
this.UpdateButton.Size = new System.Drawing.Size(126, 51);
this.UpdateButton.TabIndex = 4;
this.UpdateButton.Text = "Обновить";
this.UpdateButton.UseVisualStyleBackColor = true;
@@ -108,9 +113,10 @@
//
// DeleteButton
//
this.DeleteButton.Location = new System.Drawing.Point(590, 143);
this.DeleteButton.Location = new System.Drawing.Point(674, 191);
this.DeleteButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.DeleteButton.Name = "DeleteButton";
this.DeleteButton.Size = new System.Drawing.Size(110, 38);
this.DeleteButton.Size = new System.Drawing.Size(126, 51);
this.DeleteButton.TabIndex = 3;
this.DeleteButton.Text = "Удалить";
this.DeleteButton.UseVisualStyleBackColor = true;
@@ -118,9 +124,10 @@
//
// ChangeButton
//
this.ChangeButton.Location = new System.Drawing.Point(590, 82);
this.ChangeButton.Location = new System.Drawing.Point(674, 109);
this.ChangeButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ChangeButton.Name = "ChangeButton";
this.ChangeButton.Size = new System.Drawing.Size(110, 38);
this.ChangeButton.Size = new System.Drawing.Size(126, 51);
this.ChangeButton.TabIndex = 2;
this.ChangeButton.Text = "Изменить";
this.ChangeButton.UseVisualStyleBackColor = true;
@@ -128,9 +135,10 @@
//
// AddButton
//
this.AddButton.Location = new System.Drawing.Point(590, 22);
this.AddButton.Location = new System.Drawing.Point(674, 29);
this.AddButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.AddButton.Name = "AddButton";
this.AddButton.Size = new System.Drawing.Size(110, 38);
this.AddButton.Size = new System.Drawing.Size(126, 51);
this.AddButton.TabIndex = 1;
this.AddButton.Text = "Добавить";
this.AddButton.UseVisualStyleBackColor = true;
@@ -159,7 +167,8 @@
dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.DataGridView.DefaultCellStyle = dataGridViewCellStyle2;
this.DataGridView.Location = new System.Drawing.Point(6, 22);
this.DataGridView.Location = new System.Drawing.Point(7, 29);
this.DataGridView.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.DataGridView.Name = "DataGridView";
dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Control;
@@ -169,32 +178,39 @@
dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.DataGridView.RowHeadersDefaultCellStyle = dataGridViewCellStyle3;
this.DataGridView.RowHeadersWidth = 51;
this.DataGridView.RowTemplate.Height = 25;
this.DataGridView.Size = new System.Drawing.Size(561, 322);
this.DataGridView.Size = new System.Drawing.Size(641, 429);
this.DataGridView.TabIndex = 0;
//
// ID
//
this.ID.HeaderText = "ID";
this.ID.MinimumWidth = 6;
this.ID.Name = "ID";
this.ID.Visible = false;
this.ID.Width = 125;
//
// ComponentNameField
//
this.ComponentNameField.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ComponentNameField.HeaderText = "Компонент";
this.ComponentNameField.MinimumWidth = 6;
this.ComponentNameField.Name = "ComponentNameField";
//
// CountField
//
this.CountField.HeaderText = "Количество";
this.CountField.MinimumWidth = 6;
this.CountField.Name = "CountField";
this.CountField.Width = 125;
//
// ButtonCancel
//
this.ButtonCancel.Location = new System.Drawing.Point(602, 446);
this.ButtonCancel.Location = new System.Drawing.Point(688, 595);
this.ButtonCancel.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ButtonCancel.Name = "ButtonCancel";
this.ButtonCancel.Size = new System.Drawing.Size(110, 34);
this.ButtonCancel.Size = new System.Drawing.Size(126, 45);
this.ButtonCancel.TabIndex = 7;
this.ButtonCancel.Text = "Отмена";
this.ButtonCancel.UseVisualStyleBackColor = true;
@@ -202,9 +218,10 @@
//
// SaveButton
//
this.SaveButton.Location = new System.Drawing.Point(486, 446);
this.SaveButton.Location = new System.Drawing.Point(555, 595);
this.SaveButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.SaveButton.Name = "SaveButton";
this.SaveButton.Size = new System.Drawing.Size(110, 34);
this.SaveButton.Size = new System.Drawing.Size(126, 45);
this.SaveButton.TabIndex = 8;
this.SaveButton.Text = "Сохранить";
this.SaveButton.UseVisualStyleBackColor = true;
@@ -212,9 +229,9 @@
//
// FormCar
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(746, 498);
this.ClientSize = new System.Drawing.Size(853, 664);
this.Controls.Add(this.SaveButton);
this.Controls.Add(this.ButtonCancel);
this.Controls.Add(this.ComponentsGroupBox);
@@ -222,8 +239,10 @@
this.Controls.Add(this.CarNameTextBox);
this.Controls.Add(this.PriceLabel);
this.Controls.Add(this.CarNameLabel);
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Name = "FormCar";
this.Text = "Изделие";
this.Load += new System.EventHandler(this.FormCar_Load);
this.ComponentsGroupBox.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).EndInit();
this.ResumeLayout(false);

View File

@@ -1,5 +1,6 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.DI;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantDataModels.Models;
using Microsoft.Extensions.Logging;
@@ -83,7 +84,7 @@ namespace AutomobilePlant
private void AddButton_Click(object sender, EventArgs e)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormCarComponent));
DependencyManager.Instance.Resolve<FormCarComponent>();
if (service is FormCarComponent form)
{
if (form.ShowDialog() == DialogResult.OK)
@@ -112,7 +113,7 @@ namespace AutomobilePlant
if (DataGridView.SelectedRows.Count == 1)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormCarComponent));
DependencyManager.Instance.Resolve<FormCarComponent>();
if (service is FormCarComponent form)
{
int id =

View File

@@ -1,64 +1,4 @@
<?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.
-->
<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">

View File

@@ -10,6 +10,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AutomobilePlantContracts.DI;
namespace AutomobilePlant
{
@@ -34,15 +35,7 @@ namespace AutomobilePlant
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
DataGridView.DataSource = list;
DataGridView.Columns["Id"].Visible = false;
DataGridView.Columns["CarName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
DataGridView.Columns["CarComponents"].Visible = false;
}
DataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка изделий");
@@ -56,7 +49,7 @@ namespace AutomobilePlant
private void AddButton_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCar));
var service = DependencyManager.Instance.Resolve<FormCar>();
if (service is FormCar form)
{
@@ -70,7 +63,7 @@ namespace AutomobilePlant
{
if (DataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCar));
var service = DependencyManager.Instance.Resolve<FormCar>();
if (service is FormCar form)
{

View File

@@ -1,4 +1,5 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlant;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
@@ -26,13 +27,7 @@ namespace AbstractShopView
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
dataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка клиентов");
}
catch (Exception ex)

View File

@@ -1,5 +1,6 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.DI;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@@ -32,14 +33,7 @@ namespace AutomobilePlant
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
DataGridView.DataSource = list;
DataGridView.Columns["Id"].Visible = false;
DataGridView.Columns["ComponentName"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
}
DataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка компонентов");
}
catch (Exception ex)
@@ -52,7 +46,7 @@ namespace AutomobilePlant
private void AddButton_Click(object sender, EventArgs e)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormComponent));
DependencyManager.Instance.Resolve<FormComponent>();
if (service is FormComponent form)
{
if (form.ShowDialog() == DialogResult.OK)
@@ -66,7 +60,7 @@ namespace AutomobilePlant
if (DataGridView.SelectedRows.Count == 1)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormComponent));
DependencyManager.Instance.Resolve<FormComponent>();
if (service is FormComponent form)
{
form.Id =

View File

@@ -1,5 +1,6 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.DI;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@@ -33,14 +34,7 @@ namespace AutomobilePlant
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
DataGridView.DataSource = list;
DataGridView.Columns["Id"].Visible = false;
DataGridView.Columns["ImplementerFIO"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
}
DataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка исполнителей");
}
catch (Exception ex)
@@ -53,7 +47,7 @@ namespace AutomobilePlant
private void AddButton_Click(object sender, EventArgs e)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormImplementer));
DependencyManager.Instance.Resolve<FormImplementer>();
if (service is FormImplementer form)
{
if (form.ShowDialog() == DialogResult.OK)
@@ -67,7 +61,7 @@ namespace AutomobilePlant
if (DataGridView.SelectedRows.Count == 1)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormImplementer));
DependencyManager.Instance.Resolve<FormImplementer>();
if (service is FormImplementer form)
{
form.Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);

View File

@@ -39,10 +39,12 @@
this.клиентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.исполнителиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.начатьРаботуToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.письмаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.DataGridView = new System.Windows.Forms.DataGridView();
this.CreateOrderButton = new System.Windows.Forms.Button();
this.IssuedOrderButton = new System.Windows.Forms.Button();
this.UpdateListButton = new System.Windows.Forms.Button();
this.бекапToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.MenuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit();
this.SuspendLayout();
@@ -55,7 +57,9 @@
this.отчетыToolStripMenuItem,
this.клиентыToolStripMenuItem,
this.исполнителиToolStripMenuItem,
this.начатьРаботуToolStripMenuItem});
this.начатьРаботуToolStripMenuItem,
this.письмаToolStripMenuItem,
this.бекапToolStripMenuItem});
this.MenuStrip.Location = new System.Drawing.Point(0, 0);
this.MenuStrip.Name = "MenuStrip";
this.MenuStrip.Padding = new System.Windows.Forms.Padding(7, 3, 0, 3);
@@ -138,6 +142,13 @@
this.начатьРаботуToolStripMenuItem.Text = "Начать работу";
this.начатьРаботуToolStripMenuItem.Click += new System.EventHandler(this.начатьРаботуToolStripMenuItem_Click);
//
// письмаToolStripMenuItem
//
this.письмаToolStripMenuItem.Name = "письмаToolStripMenuItem";
this.письмаToolStripMenuItem.Size = new System.Drawing.Size(77, 24);
this.письмаToolStripMenuItem.Text = "Письма";
this.письмаToolStripMenuItem.Click += new System.EventHandler(this.письмаToolStripMenuItem_Click);
//
// DataGridView
//
this.DataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
@@ -182,6 +193,13 @@
this.UpdateListButton.UseVisualStyleBackColor = true;
this.UpdateListButton.Click += new System.EventHandler(this.UpdateListButton_Click);
//
// бекапToolStripMenuItem
//
this.бекапToolStripMenuItem.Name = "бекапToolStripMenuItem";
this.бекапToolStripMenuItem.Size = new System.Drawing.Size(64, 24);
this.бекапToolStripMenuItem.Text = "Бекап";
this.бекапToolStripMenuItem.Click += new System.EventHandler(this.бекапToolStripMenuItem_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
@@ -222,5 +240,7 @@
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem;
private ToolStripMenuItem начатьРаботуToolStripMenuItem;
private ToolStripMenuItem письмаToolStripMenuItem;
private ToolStripMenuItem бекапToolStripMenuItem;
}
}

View File

@@ -1,7 +1,9 @@
using AbstractShopView;
using AutomobilePlantBusinessLogic.BusinessLogics;
using AutomobilePlantBusinessLogic.MailWorker;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.DI;
using AutomobilePlantDataModels.Enums;
using Microsoft.Extensions.Logging;
using System;
@@ -22,14 +24,16 @@ namespace AutomobilePlant
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess;
private readonly IBackUpLogic _backUpLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
_backUpLogic = backUpLogic;
}
private void FormMain_Load(object sender, EventArgs e)
@@ -43,15 +47,7 @@ namespace AutomobilePlant
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
DataGridView.DataSource = list;
DataGridView.Columns["CarId"].Visible = false;
DataGridView.Columns["ClientId"].Visible = false;
DataGridView.Columns["ImplementerId"].Visible = false;
}
DataGridView.FillAndConfigGrid(_orderLogic.ReadList(null));
_logger.LogInformation("Загрузка заказов");
}
@@ -64,7 +60,7 @@ namespace AutomobilePlant
private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
var service = DependencyManager.Instance.Resolve<FormComponents>();
if (service is FormComponents form)
{
@@ -74,7 +70,7 @@ namespace AutomobilePlant
private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCars));
var service = DependencyManager.Instance.Resolve<FormCars>();
if (service is FormCars form)
{
@@ -84,7 +80,7 @@ namespace AutomobilePlant
private void CreateOrderButton_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
var service = DependencyManager.Instance.Resolve<FormCreateOrder>();
if (service is FormCreateOrder form)
{
@@ -216,7 +212,7 @@ namespace AutomobilePlant
private void ComponentCarsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportCarComponents));
var service = DependencyManager.Instance.Resolve<FormReportCarComponents>();
if (service is FormReportCarComponents form)
{
form.ShowDialog();
@@ -225,7 +221,7 @@ namespace AutomobilePlant
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
var service = DependencyManager.Instance.Resolve<FormReportOrders>();
if (service is FormReportOrders form)
{
form.ShowDialog();
@@ -234,7 +230,7 @@ namespace AutomobilePlant
private void клиентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClients));
var service = DependencyManager.Instance.Resolve<FormClients>();
if (service is FormClients form)
{
form.ShowDialog();
@@ -243,7 +239,7 @@ namespace AutomobilePlant
private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
var service = DependencyManager.Instance.Resolve<FormImplementers>();
if (service is FormImplementers form)
{
form.ShowDialog();
@@ -252,9 +248,28 @@ namespace AutomobilePlant
private void начатьРаботуToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
_workProcess.DoWork(DependencyManager.Instance.Resolve<IImplementerLogic>(), _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void письмаToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = DependencyManager.Instance.Resolve<FormMessages>();
if (service is FormMessages form)
{
form.ShowDialog();
}
}
private void бекапToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new FolderBrowserDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
_backUpLogic.CreateBackUp(new BackUpSaveBinidngModel { FolderName = dialog.SelectedPath});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}

View File

@@ -0,0 +1,72 @@
namespace AutomobilePlant
{
partial class FormMessages
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dataGridView = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.AllowUserToAddRows = false;
this.dataGridView.AllowUserToDeleteRows = false;
this.dataGridView.BackgroundColor = System.Drawing.SystemColors.ControlLightLight;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Dock = System.Windows.Forms.DockStyle.Left;
this.dataGridView.Location = new System.Drawing.Point(0, 0);
this.dataGridView.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.dataGridView.Name = "dataGridView";
this.dataGridView.ReadOnly = true;
this.dataGridView.RowHeadersVisible = false;
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView.Size = new System.Drawing.Size(617, 480);
this.dataGridView.TabIndex = 0;
//
// FormMessages
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(619, 480);
this.Controls.Add(this.dataGridView);
this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.Name = "FormMessages";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Клиенты";
this.Load += new System.EventHandler(this.FormMessages_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.DataGridView dataGridView;
}
}

View File

@@ -0,0 +1,52 @@
using AbstractShopView;
using AutomobilePlantBusinessLogic.BusinessLogics;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AutomobilePlant
{
public partial class FormMessages : Form
{
private readonly ILogger _logger;
private readonly IMessageInfoLogic _logic;
public FormMessages(ILogger<FormClients> logger, IMessageInfoLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormMessages_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
dataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка клиентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки клиентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

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>

View File

@@ -9,13 +9,16 @@ using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System.Drawing;
using AbstractShopView;
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantBusinessLogic.MailWorker;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.DI;
namespace AutomobilePlant
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
@@ -25,49 +28,74 @@ namespace AutomobilePlant
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
InitDependency();
try
{
var mailSender = DependencyManager.Instance.Resolve<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty,
SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty,
SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]),
PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty,
PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"])
});
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000);
}
catch (Exception ex)
{
var logger = DependencyManager.Instance.Resolve<ILogger>();
logger?.LogError(ex, "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>");
}
Application.Run(DependencyManager.Instance.Resolve<FormMain>());
}
private static void ConfigureServices(ServiceCollection services)
private static void InitDependency()
{
services.AddLogging(option =>
DependencyManager.InitDependency();
DependencyManager.Instance.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<ICarStorage, CarStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IComponentLogic, ComponentLogic>();
DependencyManager.Instance.RegisterType<IOrderLogic, OrderLogic>();
DependencyManager.Instance.RegisterType<ICarLogic, CarLogic>();
DependencyManager.Instance.RegisterType<IReportLogic, ReportLogic>();
DependencyManager.Instance.RegisterType<IMessageInfoLogic, MessageLogic>();
DependencyManager.Instance.RegisterType<IClientLogic, ClientLogic>();
DependencyManager.Instance.RegisterType<IImplementerLogic, ImplementerLogic>();
DependencyManager.Instance.RegisterType<IBackUpLogic, BackUpLogic>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<ICarLogic, CarLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
DependencyManager.Instance.RegisterType<AbstractMailWorker, MailKitWorker>(true);
DependencyManager.Instance.RegisterType<IWorkProcess, WorkModeling>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
DependencyManager.Instance.RegisterType<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormCar>();
services.AddTransient<FormCarComponent>();
services.AddTransient<FormCars>();
services.AddTransient<FormReportCarComponents>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormClients>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormImplementers>();
DependencyManager.Instance.RegisterType<FormMain>();
DependencyManager.Instance.RegisterType<FormComponent>();
DependencyManager.Instance.RegisterType<FormComponents>();
DependencyManager.Instance.RegisterType<FormCreateOrder>();
DependencyManager.Instance.RegisterType<FormCar>();
DependencyManager.Instance.RegisterType<FormCarComponent>();
DependencyManager.Instance.RegisterType<FormCars>();
DependencyManager.Instance.RegisterType<FormReportCarComponents>();
DependencyManager.Instance.RegisterType<FormReportOrders>();
DependencyManager.Instance.RegisterType<FormClients>();
DependencyManager.Instance.RegisterType<FormImplementer>();
DependencyManager.Instance.RegisterType<FormImplementers>();
DependencyManager.Instance.RegisterType<FormMessages>();
}
private static void MailCheck(object obj) => DependencyManager.Instance.Resolve<AbstractMailWorker>()?.MailCheck();
}
}

View File

@@ -29,5 +29,7 @@ namespace AutomobilePlantDataBaseImplements
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
public virtual DbSet<MessageInfo> Messages { set; get; }
}
}

View File

@@ -19,4 +19,8 @@
<ProjectReference Include="..\AbstractAutoContracts\AutomobilePlantContracts.csproj" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project>

View File

@@ -0,0 +1,28 @@
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantContracts.DI;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantDataBaseImplements.Implements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantDataBaseImplements
{
public class DBImplementationExtension : IImplementationExtension
{
public int Priority => 2;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IComponentStorage, ComponentStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<ICarStorage, CarStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@@ -0,0 +1,32 @@
using AutomobilePlantContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantDataBaseImplements.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
using var context = new AutoPlantDataBase();
return context.Set<T>().ToList();
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
var assembly = typeof(BackUpInfo).Assembly;
var types = assembly.GetTypes();
foreach (var type in types)
{
if (type.IsClass && type.GetInterface(modelInterfaceName) != null)
{
return type;
}
}
return null;
}
}
}

View File

@@ -34,7 +34,7 @@ namespace AutomobilePlantDataBaseImplements.Implements
.Where(x => x.ClientFIO.Contains(model.ClientFIO))
.Select(x => x.GetViewModel)
.ToList();
}else if (!string.IsNullOrEmpty(model.Email))
}else if (!string.IsNullOrEmpty(model.Email)) // Поиск клиента по логину
{
return context.Clients
.Where(x => x.Email.Contains(model.Email))

View File

@@ -0,0 +1,68 @@
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.ViewModel;
using AutomobilePlantDataBaseImplements.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantDataBaseImplements.Implements
{
public class MessageStorage : IMessageInfoStorage
{
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (string.IsNullOrEmpty(model.MessageId) )
{
return null;
}
using var context = new AutoPlantDataBase();
return context.Messages
.Include(x => x.client)
.FirstOrDefault(x => x.MessageId.Equals(model.MessageId))
?.GetViewModel;
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
if (!model.ClientId.HasValue)
{
return new();
}
using var context = new AutoPlantDataBase();
return context.Messages
.Include(x => x.client)
.Where(x => x.ClientId == model.ClientId)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<MessageInfoViewModel> GetFullList()
{
using var context = new AutoPlantDataBase();
return context.Messages
.Include(x => x.client)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
using var context = new AutoPlantDataBase();
var newMes = MessageInfo.Create(model);
if (newMes == null)
{
return null;
}
context.Messages.Add(newMes);
context.SaveChanges();
return newMes.GetViewModel;
}
}
}

View File

@@ -0,0 +1,312 @@
// <auto-generated />
using System;
using AutomobilePlantDataBaseImplements;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AutomobilePlantDataBaseImplements.Migrations
{
[DbContext(typeof(AutoPlantDataBase))]
[Migration("20230427155513_EmailAdd")]
partial class EmailAdd
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Car", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("CarName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Cars");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.CarComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("CarId")
.HasColumnType("integer");
b.Property<int>("ComponentId")
.HasColumnType("integer");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("ComponentId");
b.ToTable("CarComponents");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Cost")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Qualification")
.HasColumnType("integer");
b.Property<int>("WorkExperience")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("text");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("ClientId")
.IsRequired()
.HasColumnType("integer");
b.Property<DateTime>("DateDelivery")
.HasColumnType("timestamp with time zone");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("text");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("CarId")
.HasColumnType("integer");
b.Property<string>("CarName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ClientId")
.HasColumnType("integer");
b.Property<string>("ClientName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<DateTime>("DateCreate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("DateImplement")
.HasColumnType("timestamp with time zone");
b.Property<int?>("ImplementerId")
.HasColumnType("integer");
b.Property<string>("ImplementerName")
.HasColumnType("text");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.CarComponent", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Car", "Car")
.WithMany("Components")
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AutomobilePlantDataBaseImplements.Models.Component", "Component")
.WithMany("CarComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Car");
b.Navigation("Component");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.MessageInfo", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Client", "client")
.WithMany("Messages")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("client");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Order", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Car", "car")
.WithMany("Orders")
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AutomobilePlantDataBaseImplements.Models.Client", "client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AutomobilePlantDataBaseImplements.Models.Implementer", "implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("car");
b.Navigation("client");
b.Navigation("implementer");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Car", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Client", b =>
{
b.Navigation("Messages");
b.Navigation("Orders");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Component", b =>
{
b.Navigation("CarComponents");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Implementer", b =>
{
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,49 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AutomobilePlantDataBaseImplements.Migrations
{
/// <inheritdoc />
public partial class EmailAdd : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Messages",
columns: table => new
{
MessageId = table.Column<string>(type: "text", nullable: false),
ClientId = table.Column<int>(type: "integer", nullable: false),
SenderName = table.Column<string>(type: "text", nullable: false),
DateDelivery = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
Subject = table.Column<string>(type: "text", nullable: false),
Body = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Messages", x => x.MessageId);
table.ForeignKey(
name: "FK_Messages_Clients_ClientId",
column: x => x.ClientId,
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Messages_ClientId",
table: "Messages",
column: "ClientId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Messages");
}
}
}

View File

@@ -0,0 +1,309 @@
// <auto-generated />
using System;
using AutomobilePlantDataBaseImplements;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AutomobilePlantDataBaseImplements.Migrations
{
[DbContext(typeof(AutoPlantDataBase))]
[Migration("20230427192728_EmailAdd2")]
partial class EmailAdd2
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Car", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("CarName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Cars");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.CarComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("CarId")
.HasColumnType("integer");
b.Property<int>("ComponentId")
.HasColumnType("integer");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("ComponentId");
b.ToTable("CarComponents");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Cost")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Qualification")
.HasColumnType("integer");
b.Property<int>("WorkExperience")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("text");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("ClientId")
.HasColumnType("integer");
b.Property<DateTime>("DateDelivery")
.HasColumnType("timestamp with time zone");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("text");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("CarId")
.HasColumnType("integer");
b.Property<string>("CarName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ClientId")
.HasColumnType("integer");
b.Property<string>("ClientName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<DateTime>("DateCreate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("DateImplement")
.HasColumnType("timestamp with time zone");
b.Property<int?>("ImplementerId")
.HasColumnType("integer");
b.Property<string>("ImplementerName")
.HasColumnType("text");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.CarComponent", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Car", "Car")
.WithMany("Components")
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AutomobilePlantDataBaseImplements.Models.Component", "Component")
.WithMany("CarComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Car");
b.Navigation("Component");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.MessageInfo", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Client", "client")
.WithMany("Messages")
.HasForeignKey("ClientId");
b.Navigation("client");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Order", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Car", "car")
.WithMany("Orders")
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AutomobilePlantDataBaseImplements.Models.Client", "client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AutomobilePlantDataBaseImplements.Models.Implementer", "implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("car");
b.Navigation("client");
b.Navigation("implementer");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Car", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Client", b =>
{
b.Navigation("Messages");
b.Navigation("Orders");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Component", b =>
{
b.Navigation("CarComponents");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Implementer", b =>
{
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,59 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AutomobilePlantDataBaseImplements.Migrations
{
/// <inheritdoc />
public partial class EmailAdd2 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Messages_Clients_ClientId",
table: "Messages");
migrationBuilder.AlterColumn<int>(
name: "ClientId",
table: "Messages",
type: "integer",
nullable: true,
oldClrType: typeof(int),
oldType: "integer");
migrationBuilder.AddForeignKey(
name: "FK_Messages_Clients_ClientId",
table: "Messages",
column: "ClientId",
principalTable: "Clients",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Messages_Clients_ClientId",
table: "Messages");
migrationBuilder.AlterColumn<int>(
name: "ClientId",
table: "Messages",
type: "integer",
nullable: false,
defaultValue: 0,
oldClrType: typeof(int),
oldType: "integer",
oldNullable: true);
migrationBuilder.AddForeignKey(
name: "FK_Messages_Clients_ClientId",
table: "Messages",
column: "ClientId",
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}

View File

@@ -140,6 +140,36 @@ namespace AutomobilePlantDataBaseImplements.Migrations
b.ToTable("Implementers");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("text");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("ClientId")
.HasColumnType("integer");
b.Property<DateTime>("DateDelivery")
.HasColumnType("timestamp with time zone");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("text");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Order", b =>
{
b.Property<int>("Id")
@@ -213,6 +243,15 @@ namespace AutomobilePlantDataBaseImplements.Migrations
b.Navigation("Component");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.MessageInfo", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Client", "client")
.WithMany("Messages")
.HasForeignKey("ClientId");
b.Navigation("client");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Order", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Car", "car")
@@ -247,6 +286,8 @@ namespace AutomobilePlantDataBaseImplements.Migrations
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Client", b =>
{
b.Navigation("Messages");
b.Navigation("Orders");
});

View File

@@ -8,17 +8,22 @@ using System.Text;
using System.Threading.Tasks;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModel;
using System.Runtime.Serialization;
namespace AutomobilePlantDataBaseImplements.Models
{
[DataContract]
public class Car : ICarModel
{
[DataMember]
public int Id { get; set; }
[Required]
[DataMember]
public string CarName { get; set; } = string.Empty;
[Required]
[DataMember]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _carComponents = null;

View File

@@ -2,22 +2,28 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantDataBaseImplements.Models
{
public class CarComponent
{
public int Id { get; set; }
[Required]
public int CarId { get; set; }
[Required]
public int ComponentId { get; set; }
[Required]
public int Count { get; set; }
public virtual Component Component { get; set; } = new();

View File

@@ -10,26 +10,35 @@ using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace AutomobilePlantDataBaseImplements.Models
{
[DataContract]
public class Client : IClientModel
{
[DataMember]
public int Id { get; set; }
[Required]
[DataMember]
public string ClientFIO { get; set; } = string.Empty;
[Required]
[DataMember]
public string Email { get; set; } = string.Empty;
[Required]
[DataMember]
public string Password { get; set; } = string.Empty;
[ForeignKey("ClientId")]
public virtual List<Order> Orders { get; set; } = new();
[ForeignKey("ClientId")]
public virtual List<MessageInfo> Messages { get; set; } = new();
public static Client Create( ClientBindingModel model)
{
return new Client()

View File

@@ -8,17 +8,22 @@ using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace AutomobilePlantDataBaseImplements.Models
{
[DataContract]
public class Component : IComponentModel
{
[DataMember]
public int Id { get; private set; }
[Required]
[DataMember]
public string ComponentName { get; private set; } = string.Empty;
[Required]
[DataMember]
public double Cost { get; set; }
[ForeignKey("ComponentId")]

View File

@@ -8,22 +8,29 @@ using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace AutomobilePlantDataBaseImplements.Models
{
[DataContract]
public class Implementer : IImplementerModel
{
[DataMember]
public int Id { get; set; }
[Required]
[DataMember]
public string ImplementerFIO { get; set; } = string.Empty;
[Required]
[DataMember]
public int WorkExperience { get; set; }
[Required]
[DataMember]
public int Qualification { get; set; }
[Required]
[DataMember]
public string Password { get; set; } = string.Empty;

View File

@@ -0,0 +1,61 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModel;
using AutomobilePlantDataModels.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantDataBaseImplements.Models
{
[DataContract]
public class MessageInfo : IMessageInfoModel
{
[Key]
[DataMember]
public string MessageId { get; set; } = string.Empty;
[DataMember]
public int? ClientId { get; set; }
public Client? client { get; private set; }
[DataMember]
public string SenderName { get; set; } = string.Empty;
[DataMember]
public DateTime DateDelivery { get; set; }
[DataMember]
public string Subject { get; set; } = string.Empty;
[DataMember]
public string Body { get; set; } = string.Empty;
public static MessageInfo? Create(MessageInfoBindingModel? model)
{
if (model == null)
{
return null;
}
return new MessageInfo()
{ Id = model.Id,
MessageId = model.MessageId,
ClientId = model.ClientId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
Subject = model.Subject,
Body = model.Body,
};
}
public MessageInfoViewModel GetViewModel => new()
{ Id = Id,
MessageId = MessageId,
ClientId = ClientId,
SenderName = SenderName,
DateDelivery = DateDelivery,
Subject = Subject,
Body = Body,
};
[NotMapped]
public int Id {get; set;}
}
}

View File

@@ -8,33 +8,48 @@ using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantDataBaseImplements.Models
{
[DataContract]
public class Order : IOrderModel
{
[DataMember]
public int Id { get; private set; }
[Required]
[DataMember]
public int CarId { get; private set; }
[Required]
[DataMember]
public int ClientId { get; private set; }
[DataMember]
public string ClientName { get; private set; } = string.Empty;
[DataMember]
public int? ImplementerId { get; private set; }
[DataMember]
public string? ImplementerName { get; private set; } = string.Empty;
[DataMember]
public string CarName { get; private set; } = string.Empty;
public Client client { get; private set; }
public Car car { get; private set; }
public Implementer? implementer { get; private set; }
[Required]
[DataMember]
public int Count { get; private set; }
[Required]
[DataMember]
public double Sum { get; private set; }
[Required]
[DataMember]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[Required]
[DataMember]
public DateTime DateCreate { get; private set; } = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
[DataMember]
public DateTime? DateImplement { get; private set; }
public static Order? Create(OrderBindingModel? model)

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
@@ -11,4 +11,8 @@
<ProjectReference Include="..\AbstractAutoDataModels\AutomobilePlantDataModels.csproj" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project>

View File

@@ -16,11 +16,13 @@ namespace AutomomilePlantFileImplement
private readonly string CarFileName = "Car.xml";
private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
private readonly string MessageFileName = "Message.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Car> Cars { get; private set; }
public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; }
public List<MessageInfo> Messages { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@@ -39,6 +41,8 @@ namespace AutomomilePlantFileImplement
"Cars", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x
=> x.GetXElement);
public void SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x
=> x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x =>
@@ -50,6 +54,7 @@ namespace AutomomilePlantFileImplement
Implementers = LoadData(ImplementerFileName, "Implementers", x =>
Implementer.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Messages = LoadData(MessageFileName, "Message", x => MessageInfo.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName,
Func<XElement, T> selectFunction)

View File

@@ -0,0 +1,28 @@
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantContracts.DI;
using AutomobilePlantContracts.StoragesContracts;
using AutomomilePlantFileImplement.Implements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomomilePlantFileImplement
{
public class FileImplementationExtension : IImplementationExtension
{
public int Priority => 1;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IComponentStorage, ComponentStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<ICarStorage, CarStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@@ -0,0 +1,35 @@
using AutomobilePlantContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AutomomilePlantFileImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
var context = DataFileSingleton.GetInstance();
return (List<T>?)context.GetType().GetProperties().FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetProperty("Item").PropertyType == typeof(T)).GetValue(context);
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
var assembly = typeof(BackUpInfo).Assembly;
var types = assembly.GetTypes();
foreach (var type in types)
{
if (type.IsClass && type.GetInterface(modelInterfaceName) != null)
{
return type;
}
}
return null;
}
}
}

View File

@@ -0,0 +1,74 @@
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.ViewModel;
using AutomobilePlantDataModels.Models;
using AutomomilePlantFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomomilePlantFileImplement.Implements
{
public class MessageStorage : IMessageInfoStorage
{
private readonly DataFileSingleton source;
public MessageStorage()
{
source = DataFileSingleton.GetInstance();
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (string.IsNullOrEmpty(model.MessageId) )
{
return null;
}
return source.Messages
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.MessageId) && x.MessageId.Equals(model.MessageId)))
?.GetViewModel;
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
if (!model.ClientId.HasValue)
{
return new();
}
return source.Messages
.Where(x => x.ClientId== model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
}
public List<MessageInfoViewModel> GetFullList()
{
return source.Messages
.Select(x => x.GetViewModel)
.ToList();
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
if (source.Messages.Count > 0)
{
var id = source.Messages.Count + 1;
model.MessageId = id.ToString();
}
else
model.MessageId = "1";
var newMes = MessageInfo.Create(model);
if (newMes == null)
{
return null;
}
source.Messages.Add(newMes);
source.SaveMessages();
return newMes.GetViewModel;
}
}
}

View File

@@ -4,16 +4,21 @@ using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AutomomilePlantFileImplement.Models
{
[DataContract]
public class Car : ICarModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string CarName { get; private set; } = string.Empty;
[DataMember]
public double Price { get; private set; }
public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _carComponents =

View File

@@ -5,17 +5,23 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AutomomilePlantFileImplement.Models
{
[DataContract]
public class Client : IClientModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string ClientFIO { get; private set; } = string.Empty;
[DataMember]
public string Email { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty;
public static Client? Create(ClientBindingModel model)
{

View File

@@ -4,16 +4,21 @@ using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AutomomilePlantFileImplement.Models
{
[DataContract]
public class Component : IComponentModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string ComponentName { get; private set; } = string.Empty;
[DataMember]
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel model)
{

View File

@@ -4,18 +4,25 @@ using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AutomomilePlantFileImplement.Models
{
[DataContract]
public class Implementer : IImplementerModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string ImplementerFIO { get; private set; } = string.Empty;
[DataMember]
public int WorkExperience { get; set; }
[DataMember]
public int Qualification { get; set; }
[DataMember]
public string Password { get; private set; } = string.Empty;
public static Implementer? Create(ImplementerBindingModel model)
{

View File

@@ -0,0 +1,86 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModel;
using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AutomomilePlantFileImplement.Models
{
[DataContract]
public class MessageInfo : IMessageInfoModel
{
[DataMember]
public string MessageId {get;set;} = string.Empty;
public int? ClientId { get; set; }
[DataMember]
public string SenderName { get; set; } = string.Empty;
[DataMember]
public DateTime DateDelivery { get; set; }
[DataMember]
public string Subject { get; set; } = string.Empty;
[DataMember]
public string Body { get; set;} = string.Empty;
public static MessageInfo? Create(MessageInfoBindingModel model)
{
if (model == null)
{
return null;
}
return new MessageInfo()
{
Id = model.Id,
MessageId = model.MessageId,
ClientId = model.ClientId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
Subject = model.Subject,
Body = model.Body,
};
}
public static MessageInfo? Create(XElement element)
{
if (element == null)
{
return null;
}
return new MessageInfo()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
MessageId =element.Attribute("MessageId")!.Value,
ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value),
SenderName = element.Attribute("SenderName")!.Value,
DateDelivery = DateTime.Parse(element.Element("DateDelivery")!.Value),
Subject = element.Attribute("Subject")!.Value,
Body = element.Attribute("Body")!.Value,
};
}
public MessageInfoViewModel GetViewModel => new()
{
Id = Id,
MessageId = MessageId,
ClientId = ClientId,
SenderName = SenderName,
DateDelivery = DateDelivery,
Subject = Subject,
Body = Body,
};
public XElement GetXElement => new("MessageInfo",
new XAttribute("MessageId", MessageId),
new XAttribute("Id", Id),
new XElement("ClientId", ClientId.ToString()),
new XElement("SenderName", SenderName),
new XElement("DateDelivery", DateDelivery.ToString()),
new XElement("Subject", Subject),
new XElement("Body", Body)
);
public int Id { get; set; }
}
}

View File

@@ -5,29 +5,43 @@ using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AutomomilePlantFileImplement.Models
{
[DataContract]
public class Order : IOrderModel
{
[DataMember]
public int CarId { get; private set; }
[DataMember]
public int ClientId { get; private set; }
[DataMember]
public string ClientName { get; private set; } = string.Empty;
public string CarName { get; private set; } = string.Empty;
[DataMember]
public string CarName { get; private set; } = string.Empty;
[DataMember]
public int? ImplementerId { get; private set; }
[DataMember]
public string? ImplementerName { get; private set; } = string.Empty;
[DataMember]
public int Count { get; private set; }
[DataMember]
public double Sum { get; private set; }
[DataMember]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[DataMember]
public DateTime DateCreate { get; private set; } = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
[DataMember]
public DateTime? DateImplement { get; private set; } = null;
[DataMember]
public int Id { get; private set; }
public static Order? Create(OrderBindingModel model)

View File

@@ -13,11 +13,12 @@ namespace AutoplantRestApi.Controllers
private readonly ILogger _logger;
private readonly IClientLogic _logic;
public ClientController(IClientLogic logic, ILogger<ClientController> logger)
private IMessageInfoLogic _messageLogic;
public ClientController(IClientLogic logic, ILogger<ClientController> logger, IMessageInfoLogic messageLogic)
{
_logger = logger;
_logic = logic;
_messageLogic = messageLogic;
}
[HttpGet]
@@ -65,5 +66,21 @@ namespace AutoplantRestApi.Controllers
throw;
}
}
[HttpGet]
public List<MessageInfoViewModel>? GetMessages(int clientId)
{
try
{
return _messageLogic.ReadList(new MessageInfoSearchModel
{
ClientId = clientId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения писем клиента");
throw;
}
}
}
}

View File

@@ -1,4 +1,7 @@
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantBusinessLogic.BusinessLogics;
using AutomobilePlantBusinessLogic.MailWorker;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantDataBaseImplements.Implements;
@@ -12,11 +15,17 @@ builder.Logging.AddLog4Net("log4net.config");
// Add services to the container.
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<ICarStorage, CarStorage>();
builder.Services.AddTransient<IMessageInfoStorage, MessageStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<ICarLogic, CarLogic>();
builder.Services.AddTransient<IMessageInfoLogic, MessageLogic>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
@@ -27,7 +36,16 @@ builder.Services.AddSwaggerGen(c =>
});
var app = builder.Build();
var mailSender = app.Services.GetService<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty,
MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty,
SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty,
SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()),
PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty,
PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString())
});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{

View File

@@ -5,5 +5,12 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "labrpp89@gmail.com",
"MailPassword": "swly dzcy ccaz vdvr"
}