using System; using System.Collections.Generic; using System.Data.Entity; using System.IO; using System.Linq; using Thermo.Active.Model.DatabaseModels; using Thermo.Active.Model.DTOModels; using Thermo.Active.Model.DTOModels.AlarmModels; using static Thermo.Active.Config.ServerConfig; using static Thermo.Active.Model.Constants; namespace Thermo.Active.Database.Controllers { public class AlarmsController : IDisposable { private DatabaseContext dbCtx; public AlarmsController() { // Initialize database context dbCtx = new DatabaseContext(); } public void Dispose() { // Clear database context dbCtx.Dispose(); } public List GetPaginatedWithFilter(string title, List sources, int page, int pageSize, DateTime startDate, DateTime endDate, List userIds, Dictionary plcMessages, out int pages) { pages = 0; bool ifNoUser = false; var index = userIds.IndexOf(-1); if (userIds.IndexOf(-1) != -1) ifNoUser = true; List ncAlarmDescIds = dbCtx .AlarmDescriptions .Where(x => x.Title.Contains(title)) .Select(x => x.AlarmId) .ToList(); // Get Plc messages ids List plcAlarmDescIds = plcMessages .Where(x => x.Value.IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) //.Where(x => x.Value.Contains(title)) .Select(x => x.Key) .ToList(); // Query var occurrencesQuery = dbCtx .AlarmOccurrences .OrderBy(x => x.AlarmOccurrenceId) .Include("Users") .Where(x => x.TimeStamp >= startDate && x.TimeStamp <= endDate // Filter by date && sources.Contains(x.Source) // Check source && ((ifNoUser && x.Users.Count() == 0) || x.Users.Any(y => userIds.Any(z => z == y.UserId))) // Check user && ((x.Source == ALARM_SOURCE.NC && ncAlarmDescIds.Contains(x.AlarmDescriptionId.Value)) // Check if message is contained in NC messages || (x.Source == ALARM_SOURCE.PLC && plcAlarmDescIds.Contains(x.AlarmId))) // Check if message is contained in PLC messages ).OrderByDescending(t => t.AlarmOccurrenceId); double tmpPages = (double)occurrencesQuery.Count() / (double)pageSize; pages = (int)Math.Ceiling(tmpPages); var paginatedQuery = occurrencesQuery .Skip(page * pageSize) // Paginate .Take(pageSize) .Include("AlarmDescription") // Include foreign key .ToList(); return paginatedQuery .Select(x => (DTOAlarmHistoricModel)x) // Convert to DTOALarmHistoricModel .ToList(); } public void InsertNewOccurrences(List alarms) { dbCtx.AlarmOccurrences.AddRange(alarms); dbCtx.SaveChanges(); } public void InsertNewNcAlarmDescriptions(List descriptions) { foreach (var desc in descriptions) { // Check if description exists already var dbDesc = dbCtx.AlarmDescriptions.Where(x => x.AlarmId == desc.AlarmId).FirstOrDefault(); // If not add if (dbDesc == null) dbCtx.AlarmDescriptions.Add(desc); } dbCtx.SaveChanges(); } public void InsertNewAlarmUser(List loggedUser) { dbCtx.AlarmUsers.AddRange(loggedUser); dbCtx.SaveChanges(); // TODO check if it is the best solutions } public DTOAlarmsData GetAlarmsData(int pageSize) { // Get page numbers int pagesNumbers = dbCtx.AlarmOccurrences.Count() / pageSize; var firstAlarm = dbCtx.AlarmOccurrences.FirstOrDefault(); // Get first alarm date DateTime date = firstAlarm == null ? DateTime.Now : firstAlarm.TimeStamp; return new DTOAlarmsData { Pages = pagesNumbers, FirstDate = date }; } public AlarmOccurrencesModel FindById(int id, ALARM_SOURCE source) { return dbCtx .AlarmOccurrences .Where(x => x.AlarmId == id && x.Source == source) .FirstOrDefault(); } public void CleanTable() { int numberOfRows = CountRows(); if (numberOfRows >= ServerStartupConfig.MaxAlarmsRows) { dbCtx.Database.ExecuteSqlCommand("DELETE FROM alarm_occurrence LIMIT {0}", ServerStartupConfig.AlarmToDelete); } } public int CountRows() { return dbCtx.AlarmOccurrences.Count(); } public void EmptyAlarms() { int numberOfRows = CountRows(); dbCtx.Database.ExecuteSqlCommand("DELETE FROM alarm_occurrence LIMIT {0}", numberOfRows); } #region NOTES public List GetNotesByAlarmDescId(int alarmDescriptionId, ALARM_SOURCE source) { return dbCtx .AlarmsNotes .Where(x => x.AlarmId == alarmDescriptionId && x.Source == source) // Filter by id .Select(x => new DTOAlarmNoteModel() // Convert to return model { Id = x.NoteId, DateTime = x.DateTime, Message = x.Message, User = new DTOMessageUserModel() { Id = x.User.UserId, FirstName = x.User.FirstName, LastName = x.User.LastName, Username = x.User.Username } }) .ToList(); } public AlarmNoteModel FindNoteById(int noteId) { return dbCtx .AlarmsNotes .Where(x => x.NoteId == noteId) .Include("User") .FirstOrDefault(); } public DTOAlarmNoteModel CreateNote(int userId, int alarmId, ALARM_SOURCE source, DTONewAlarmNoteModel newNote) { // Create model AlarmNoteModel note = new AlarmNoteModel() { Message = newNote.Message, DateTime = DateTime.Now, AlarmId = alarmId, UserId = userId, Source = source }; // Add & save into database dbCtx.AlarmsNotes.Add(note); dbCtx.SaveChanges(); // Populate user data dbCtx.Entry(note).Reference(x => x.User).Load(); dbCtx.Users.Attach(note.User); return (DTOAlarmNoteModel)note; } public DTOAlarmNoteModel UpdateNote(AlarmNoteModel note, DTONewAlarmNoteModel newNote) { note.Message = newNote.Message; dbCtx.SaveChanges(); return (DTOAlarmNoteModel)note; } public void DeleteNote(int noteId) { AlarmNoteModel note = FindNoteById(noteId); dbCtx.AlarmsNotes.Remove(note); dbCtx.SaveChanges(); } #endregion NOTES #region ATTACHMENT public List FindAttachmentByAlarmDescId(int alarmId, ALARM_SOURCE source) { return dbCtx .AlarmFiles .Where(x => x.AlarmId == alarmId && x.Source == source) .ToList(); } public AlarmFileModel FindAttachmentById(int attachmentId) { return dbCtx .AlarmFiles .Where(x => x.AttachmentId == attachmentId) .FirstOrDefault(); } public AlarmFileModel AddAttachment(string fileName, string localFileName, int alarmId, int userId, ALARM_SOURCE source) { // Create obj AlarmFileModel file = new AlarmFileModel() { FileName = fileName, LocalFileName = localFileName, AlarmId = alarmId, UserId = userId, Source = source }; // Add to db dbCtx.AlarmFiles.Add(file); dbCtx.SaveChanges(); return file; } public void DeleteAttachment(int attachmentId) { // Get attachmentRow AlarmFileModel file = dbCtx .AlarmFiles .Where(x => x.AttachmentId == attachmentId) .FirstOrDefault(); if (file != null) { dbCtx.AlarmFiles.Remove(file); dbCtx.SaveChanges(); } } public void DeleteAttachment(AlarmFileModel attachment) { dbCtx.AlarmFiles.Remove(attachment); dbCtx.SaveChanges(); if (File.Exists(ALARM_ATTACHMENT_PATH + attachment.LocalFileName)) File.Delete(ALARM_ATTACHMENT_PATH + attachment.LocalFileName); } #endregion ATTACHMENT } }