using Infrastructure.Application; using Infrastructure.Data; using Infrastructure.Domain; using Infrastructure.Extensions; using Infrastructure.Web.Mvc; using IoT.Shared.Services; using IoTCenter.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace IoT.Shared.Areas.Admin.Controlls { public class SharedController : CrudController where TEntity : BaseEntity where TEditModel : EditModel where TSearchModel : PagedListModel { private readonly IServiceProvider _applicationServices; private readonly bool _isIoTCenter; public SharedController(IRepository repo, IServiceProvider applicationServices) : base(repo) { this._applicationServices = applicationServices; this._isIoTCenter = Assembly.GetEntryAssembly().GetName().Name.Contains("IoTCenter"); } public override IActionResult Add(TEditModel model) { return this.Edit(model); } public override IActionResult Edit(TEditModel model) { if (ModelState.IsValid) { try { var method = $"Edit{typeof(TEntity).Name}"; using var scope = this._applicationServices.CreateScope(); if (this._isIoTCenter) { var group = this.GetNodeNumber(model); this.ToEntity(model, null); var hub = scope.ServiceProvider.GetService>(); hub.ServerToClient(method, model, group); } else { var dataService = scope.ServiceProvider.GetService(); dataService.Edit(model); var iotNodeClient = scope.ServiceProvider.GetService(); iotNodeClient.ClientToServer(method, model, null); } return RedirectTo(); } catch (Exception ex) { ex.PrintStack(); ModelState.AddModelError("", ex.Message); } } this.ToEditModel(null, model); return View(model); } public override IActionResult Delete(List list) { foreach (var id in list) { try { var method = $"Delete{typeof(TEntity).Name}"; using var scope = this._applicationServices.CreateScope(); if (this._isIoTCenter) { var query = this._repo.ReadOnlyTable(); query = this.Include(query); var entity = query.FirstOrDefault(o => o.Id == id); var model = entity.To(); this.ToEditModel(entity, model); var group = GetNodeNumber(model); var hub = scope.ServiceProvider.GetService>(); hub.ServerToClient(method, model, group); } else { var entity = this._repo.ReadOnlyTable().FirstOrDefault(o => o.Id == id); if (entity != null) { var model = entity.To(); var dataService = scope.ServiceProvider.GetService(); dataService.Delete(model); var iotNodeClient = scope.ServiceProvider.GetService(); iotNodeClient.ClientToServer(method, model, null); } } } catch (Exception ex) { ex.PrintStack(); return RedirectTo(rawMesage: ex.Message); } } return RedirectTo(); } [ApiExplorerSettings(IgnoreApi = true)] public virtual string GetNodeNumber(TEditModel model) { throw new NotImplementedException(); } } }