Initial ref copy commit

This commit is contained in:
Samuele Locatelli
2020-09-12 16:11:43 +02:00
parent 2cb6ec6549
commit d80eeabf66
1886 changed files with 1855438 additions and 0 deletions
@@ -0,0 +1,296 @@
using Step.Model.DatabaseModels;
using Step.Model.DTOModels;
using Step.Model.DTOModels.AlarmModels;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using static Step.Model.Constants;
using static Step.Config.ServerConfig;
using System.Diagnostics;
using Step.Config;
namespace Step.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<DTOAlarmHistoricModel> GetPaginatedWithFilter(string title, List<ALARM_SOURCE> sources, int page, int pageSize, DateTime startDate, DateTime endDate, List<int?> userIds, Dictionary<int, string> plcMessages, out int pages)
{
pages = 0;
bool ifNoUser = false;
var index = userIds.IndexOf(-1);
if (userIds.IndexOf(-1) != -1)
ifNoUser = true;
List<int> ncAlarmDescIds = dbCtx
.AlarmDescriptions
.Where(x => x.Title.Contains(title))
.Select(x => x.AlarmId)
.ToList();
// Get Plc messages ids
List<int> 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<AlarmOccurrencesModel> alarms)
{
dbCtx.AlarmOccurrences.AddRange(alarms);
dbCtx.SaveChanges();
}
public void InsertNewNcAlarmDescriptions(List<AlarmDescriptionsModel> 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<AlarmUserModel> 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<DTOAlarmNoteModel> 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<AlarmFileModel> 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
}
}
@@ -0,0 +1,91 @@
using Step.Model.DatabaseModels;
using System;
using System.Collections.Generic;
using System.Linq;
using static Step.Config.ServerConfig;
namespace Step.Database.Controllers
{
public class ExternalSoftwareController : IDisposable
{
private DatabaseContext dbCtx;
public ExternalSoftwareController()
{
// Initialize database context
dbCtx = new DatabaseContext();
}
public void Dispose()
{
// Clear database context
dbCtx.Dispose();
}
public ExternalProgramModel FindById(int id)
{
return dbCtx
.ExternalPrograms
.Where(x => x.Id == id)
.SingleOrDefault();
}
public List<ExternalProgramModel> GetSoftware()
{
return dbCtx
.ExternalPrograms
.ToList();
}
public ExternalProgramModel Add(string path)
{
// Create database model
ExternalProgramModel prog = new ExternalProgramModel()
{
Path = path,
InMainMenuBar = false
};
// Add into database
dbCtx.ExternalPrograms.Add(
prog
);
// Commit changes
dbCtx.SaveChanges();
return prog;
}
public ExternalProgramModel Delete(int id)
{
// Create database model
var software = FindById(id);
if (software == null)
return null;
dbCtx.ExternalPrograms.Remove(software);
// Commit changes
dbCtx.SaveChanges();
return software;
}
public ExternalProgramModel Move(int id, bool inMainMenuBar)
{
// Create database model
var software = FindById(id);
if (software == null)
return null;
software.InMainMenuBar = inMainMenuBar;
// Commit changes
dbCtx.SaveChanges();
return software;
}
}
}
@@ -0,0 +1,99 @@
using Step.Model.DatabaseModels;
using Step.Model.DTOModels;
using System;
using System.Collections.Generic;
using System.Linq;
using static CMS_CORE_Library.Models.DataStructures;
using static Step.Config.ServerConfig;
namespace Step.Database.Controllers
{
public class FunctionsAccessController : IDisposable
{
private DatabaseContext dbCtx;
public FunctionsAccessController()
{
// Initialize database context
dbCtx = new DatabaseContext();
}
public void Dispose()
{
// Clear database context
dbCtx.Dispose();
}
public FunctionAccessModel FindEnabledFunctionByName(string functionName)
{
return dbCtx
.FunctionsAccess
.Where(x => x.Name == functionName && x.Enabled == true) // Find by name and enabled functions
.FirstOrDefault();
}
public List<DTOFunctionAccessModel> GetFunctionsAccess(int roleLevel)
{
return dbCtx
.FunctionsAccess
.Select(f => new DTOFunctionAccessModel() // Convert from database model to data transfer model
{
Id = f.FunctionAccessId,
Name = f.Name,
Area = f.Area,
Enabled = f.Enabled,
CanRead = f.ReadLevelMin <= roleLevel,
CanWrite = f.WriteLevelMin <= roleLevel
})
.ToList();
}
public List<FunctionAccessModel> FindAll()
{
return dbCtx
.FunctionsAccess
.ToList();
}
public List<DTORuntimeFunctionalityModel> FindAllFunctionsAndDisableAll()
{
return dbCtx
.FunctionsAccess
.Select( x => new DTORuntimeFunctionalityModel()
{
Id = x.FunctionAccessId,
Area = x.Area,
Name = x.Name,
Enabled = x.PlcId != -1 ? false : x.Enabled // Only PLC function has to be false
})
.ToList();
}
public List<DTORuntimeFunctionalityModel> GetFunctionsMappedWithPlc(List<FunctionalityModel> functionalityList)
{
return FunctionsAccessConfig // Find all function access
.Select(f => new DTORuntimeFunctionalityModel()
{
Id = f.FunctionAccessId,
Name = f.Name,
Area = f.Area,
Enabled = GetIfFunctionalityIsActive(functionalityList, f.PlcId, f.Enabled) // Get new enabled data
})
.ToList();
}
private bool GetIfFunctionalityIsActive(List<FunctionalityModel> functionalityList, int id, bool functionAccessIsEnabled)
{
// If id is not mapped or function is false by database config return
if (id == 0 || !functionAccessIsEnabled)
return functionAccessIsEnabled;
// Find and Return PLC data
FunctionalityModel plcFunc = functionalityList.Where(x => x.Id == id).FirstOrDefault();
if (plcFunc == null)
return false; // If not found
return plcFunc.IsActive;
}
}
}
@@ -0,0 +1,68 @@
using Step.Model.DatabaseModels;
using System;
using System.Linq;
using static Step.Config.ServerConfig;
namespace Step.Database.Controllers
{
public class MachinesController : IDisposable
{
private DatabaseContext dbCtx;
public MachinesController()
{
// Initialize database context
dbCtx = new DatabaseContext();
}
public void Dispose()
{
// Clear database context
dbCtx.Dispose();
}
public MachineModel FindById(int id)
{
return dbCtx
.Machines
.Where(x => x.MachineId == id)
.SingleOrDefault();
}
public MachineModel FindMachineByUniqueId(string uniqueId)
{
return dbCtx
.Machines
.Where(x => x.UniqueId == uniqueId)
.FirstOrDefault();
}
public MachineModel Create(string uniqueId)
{
// Create database machine model
MachineModel machine = new MachineModel()
{
Model = NcConfig.NcName,
UniqueId = uniqueId
};
// Add to database
dbCtx.Machines.Add(machine);
// Commit changes
dbCtx.SaveChanges();
return machine;
}
public void UpdateMachineName(int id, string name)
{
// Find machine by id
MachineModel machine = FindById(id);
if (machine != null)
{
// Update machine name
machine.Model = name;
dbCtx.SaveChanges();
}
}
}
}
@@ -0,0 +1,153 @@
using Step.Model.DatabaseModels;
using Step.Model.DTOModels;
using System;
using System.Collections.Generic;
using System.Linq;
using static Step.Model.Constants;
namespace Step.Database.Controllers
{
public class MachinesUsersController : IDisposable
{
private DatabaseContext dbCtx;
public MachinesUsersController()
{
// Initialize database context
dbCtx = new DatabaseContext();
}
public void Dispose()
{
// Clear database context
dbCtx.Dispose();
}
public MachineUserModel FindByUserId(int machineId, int userId)
{
return dbCtx
.MachinesUsers
.Include("Role") // TODO Add machine and user info?
.Where(x => x.MachineId == machineId && x.UserId == userId)
.FirstOrDefault();
}
public MachineUserModel FindByIdWithData(int id)
{
return dbCtx
.MachinesUsers
.Include("Role") // Join with Role, Machine, User
.Include("Machine")
.Include("User")
.Where(x => x.MachineUserId == id)
.FirstOrDefault();
}
public MachineUserModel Create(int machineId, int userId, int roleId)
{
// Create database model
MachineUserModel machine = new MachineUserModel()
{
MachineId = machineId,
UserId = userId,
RoleId = roleId
};
// Add into database
dbCtx.MachinesUsers.Add(
machine
);
// Commit changes
dbCtx.SaveChanges();
return machine;
}
public DTORoleModel GetUserRoleData(int machineId, int userId)
{
var machineUser = dbCtx
.MachinesUsers
.Include("Role")
.Where(x => x.MachineId == machineId && x.UserId == userId) // Find by machine id and user id, joining with role
.FirstOrDefault();
if (machineUser != null)
{
RoleModel role = machineUser.Role;
return new DTORoleModel()
{
Id = role.RoleId,
Name = role.Name,
Level = role.Level
};
}
return null;
}
public bool UserIsCmsAdmin(int machineId, int userId)
{
MachineUserModel user = FindByUserId(machineId, userId);
if (user.Role.RoleId == (int)ROLE_IDS.CMS_SERVICE || user.Role.RoleId == (int)ROLE_IDS.CMS_UT)
return true;
return false;
}
public bool RoleIsAdminOrHigher(int roleId)
{
var tmpRole = dbCtx.Roles
.ToList()
.First(X => X.RoleId == roleId);
if (tmpRole == null)
return false;
else
return tmpRole.Level >= MIN_ADMIN_ROLE;
}
public int CompareUsersRole(int firstUserId, int secondUserId, int machineId)
{
MachineUserModel firstUser = FindByUserId(machineId, firstUserId);
MachineUserModel secondUser = FindByUserId(machineId, secondUserId);
if (firstUser.Role.Level == secondUser.Role.Level)
return 0;
else if (firstUser.Role.Level > secondUser.Role.Level)
return 1;
else
return -1;
}
public List<DTORoleModel> GetRolesList()
{
return dbCtx
.Roles.Where(X => X.Level < MIN_CMS_ROLE)
.Select(x => new DTORoleModel()
{
Id = x.RoleId,
Name = x.Name
})
.ToList();
}
public void UpdateUserRole(int machineId, int userId, int roleId)
{
MachineUserModel machineUser = FindByUserId(machineId, userId);
if (machineUser == null)
return;
machineUser.RoleId = roleId;
dbCtx.SaveChanges();
}
public RoleModel GetUserRole(int machineId, int userId)
{
var machine = FindByUserId(machineId, userId);
if (machine != null)
return machine.Role;
return null;
}
}
}
@@ -0,0 +1,508 @@
using Step.Model.DatabaseModels;
using Step.Model.DTOModels;
using Step.Model.DTOModels.MaintenanceModels;
using Step.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using static Step.Config.ServerConfig;
using static Step.Model.Constants;
namespace Step.Database.Controllers
{
public class MaintenancesController : IDisposable
{
private DatabaseContext dbCtx;
public MaintenancesController()
{
// Initialize database context
dbCtx = new DatabaseContext();
}
public void Dispose()
{
// Clear database context
dbCtx.Dispose();
}
public List<DTOPerformModel> GetPerformedMaintenancesFromId(int maintenanceId)
{
List<DTOPerformModel> valRet = new List<DTOPerformModel>();
List<PerformedMaintenanceModel> maintList = (from maintenances in dbCtx.PerformedMaintenances
where maintenances.MaintenanceId == maintenanceId
select maintenances)
.Include("Maintainer").OrderByDescending(x => x.Date)
.ToList();
foreach (PerformedMaintenanceModel maintenance in maintList)
{
if(maintenance.ControlWord != -2)
valRet.Add(new DTOPerformModel()
{
Date = maintenance.Date,
Countervalue = (uint)Math.Ceiling(SupportFunctions.ConvertInUmeas(maintenance.CounterValue, maintenance.Maintenance.UnitOfMeasure.Value)),
ControlWord = maintenance.ControlWord,
User = maintenance.Maintainer != null ? maintenance.Maintainer.Username : null
});
}
return valRet;
}
public List<PerformedMaintenanceModel> FindLastPerformedMaintenances()
{
List<PerformedMaintenanceModel> lastMaintenances = new List<PerformedMaintenanceModel>();
// Find last performed maintenance
lastMaintenances = (from maintenances in dbCtx.PerformedMaintenances
where maintenances.Date == (from m1 in dbCtx.PerformedMaintenances // Select max data of performed maintenance
where m1.MaintenanceId == maintenances.MaintenanceId
select m1.Date
).Max()
select maintenances)
.Include("Maintainer")
.ToList();
return lastMaintenances;
}
public PerformedMaintenanceModel PerformeMaintenance(uint counterValue, int maintenanceId, int userId, int controlWord)
{
PerformedMaintenanceModel performed = new PerformedMaintenanceModel()
{
CounterValue = (int)counterValue,
Date = DateTime.Now,
MaintenanceId = maintenanceId,
MaintainerId = userId,
ControlWord = controlWord
};
dbCtx.PerformedMaintenances.Add(performed);
// Commit changes
dbCtx.SaveChanges();
return performed;
}
public MaintenanceModel FindById(int id)
{
return dbCtx
.Maintenances
.Find(id);
}
public List<MaintenanceModel> FindAll()
{
return dbCtx
.Maintenances
.ToList();
}
public MaintenanceModel Create(DTONewMaintenanceModel newMaint, int userId)
{
int counter = 0;
//fix the maintenance number to 1 (machine Counter)
if (newMaint.Type == MAINTENANCE_TYPE.MACHINE_INTERVAL)
counter = 0;
MaintenanceModel dbMaint = new MaintenanceModel()
{
MaintenanceId = GetUserMaintenanceId(dbCtx.Maintenances),
CreationDate = DateTime.Now,
CounterId = counter,
Interval = newMaint.Interval,
Deadline = newMaint.Deadline,
Description = newMaint.Description,
Title = newMaint.Title,
Type = newMaint.Type,
UnitOfMeasure = newMaint.UnitOfMeasure,
UserId = userId,
LastExpirationDate = null
};
// Add to database
dbCtx.Maintenances.Add(dbMaint);
// Commit changes
dbCtx.SaveChanges();
return dbMaint;
}
private int GetUserMaintenanceId(IEnumerable<MaintenanceModel> maintenances)
{
int max = maintenances.Select(x => x.MaintenanceId).Max();
// If there aren't user maintenance return 100
if (max < 100)
return 100;
else
return max + 1;
}
public MaintenanceModel Update(int maintenanceId, DTOUpdateMaintenanceModel newMaint)
{
MaintenanceModel dbMaint = FindById(maintenanceId);
if (dbMaint != null)
{
dbMaint.Title = newMaint.Title;
dbMaint.Description = newMaint.Description;
dbMaint.Deadline = newMaint.Deadline;
dbMaint.Interval = newMaint.Interval;
dbMaint.UnitOfMeasure = newMaint.UnitOfMeasure;
// Commit changes
dbCtx.SaveChanges();
}
return dbMaint;
}
public void Delete(int maintId)
{
MaintenanceModel maint = FindById(maintId);
Delete(maint);
}
public void Delete(MaintenanceModel maint)
{
dbCtx.Maintenances.Remove(maint);
dbCtx.SaveChanges();
}
public void CheckDifferencesFromDbAndXml()
{
List<MaintenanceModel> dbMaintenances = dbCtx
.Maintenances
.ToList();
// Find database rows that has to be deleted
List<MaintenanceModel> toDeleteMaint = dbMaintenances.Where(x => x.UserId == null &&
!MaintenancesConfig.Select(y => y.Id).Contains(x.MaintenanceId)
).ToList();
// Delete database items
foreach (var item in toDeleteMaint)
dbCtx.Maintenances.Remove(item);
dbCtx.SaveChanges();
// Find common data from
List<MaintenanceModel> toUpdateMaint = dbMaintenances.Where(x =>
MaintenancesConfig.Select(y => y.Id).Contains(x.MaintenanceId)
)
.ToList();
// Update rows
if (toUpdateMaint != null)
foreach (MaintenanceModel item in toUpdateMaint)
{
// find maintenances to be updated into db
var old = dbCtx.Maintenances.FirstOrDefault(x => x.MaintenanceId == item.MaintenanceId);
if(old != null)
// Update model
old = MaintenancesConfig.Where(x => x.Id == item.MaintenanceId).Select(x =>
{
old.MaintenanceId = x.Id;
old.Deadline = x.Deadline;
old.Interval = x.Intervall.TotalMinutes;
old.Type = (MAINTENANCE_TYPE)Enum.Parse(typeof(MAINTENANCE_TYPE), x.Type);
old.CounterId = x.CouterId;
old.UnitOfMeasure = (MAINTENANCE_UNIT_OF_MEASURE)Enum.Parse(typeof(MAINTENANCE_UNIT_OF_MEASURE), x.UnitOfMeasure);
return old;
}).FirstOrDefault();
}
dbCtx.SaveChanges();
// Get new maintenance from file
List<MaintenanceModel> toAddMaint = MaintenancesConfig
.Where(x => !toUpdateMaint.Select(y => y.MaintenanceId).Contains(x.Id))
.Select(x => new MaintenanceModel()
{
MaintenanceId = x.Id,
Deadline = x.Deadline,
Interval = x.Intervall.TotalMinutes,
Type = (MAINTENANCE_TYPE)Enum.Parse(typeof(MAINTENANCE_TYPE), x.Type),
CounterId = x.CouterId,
CreationDate = DateTime.Now,
UnitOfMeasure = (MAINTENANCE_UNIT_OF_MEASURE)Enum.Parse(typeof(MAINTENANCE_UNIT_OF_MEASURE), x.UnitOfMeasure),
UserId = null,
LastExpirationDate = null
})
.ToList();
// Add new maintenances to database
if (toAddMaint != null)
{
dbCtx.Maintenances.AddRange(toAddMaint);
dbCtx.SaveChanges();
}
}
public void UpdateLastExpirationDate(int id, DateTime expDate)
{
MaintenanceModel maintenance = FindById(id);
if (maintenance != null)
{
maintenance.LastExpirationDate = expDate;
dbCtx.SaveChanges();
}
}
#region Notes
public MaintenanceNoteModel FindNoteById(int noteId)
{
return dbCtx
.MaintenancesNotes
.Where(x => x.Id == noteId)
.Include("User")
.FirstOrDefault();
}
public List<MaintenanceNoteModel> FindNotes()
{
return dbCtx
.MaintenancesNotes
.ToList();
}
public List<DTOMaintenanceNoteModel> GetNotesByMaintId(int maintenanceId)
{
return dbCtx
.MaintenancesNotes
.Where(x => x.MaintenanceId == maintenanceId) // Filter by id
.Select(x => new DTOMaintenanceNoteModel() // Convert to return model
{
Id = x.Id,
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 DTOMaintenanceNoteModel CreateNote(int userId, int maintenanceId, DTONewMaintenanceNoteModel newNote)
{
// Create model
MaintenanceNoteModel note = new MaintenanceNoteModel()
{
Message = newNote.Message,
DateTime = DateTime.Now,
MaintenanceId = maintenanceId,
UserId = userId
};
// Add & save into database
dbCtx.MaintenancesNotes.Add(note);
dbCtx.SaveChanges();
dbCtx.Entry(note).Reference(x => x.User).Load();
dbCtx.Users.Attach(note.User);
return (DTOMaintenanceNoteModel)note;
}
public DTOMaintenanceNoteModel UpdateNote(MaintenanceNoteModel note, DTONewMaintenanceNoteModel newNote)
{
note.Message = newNote.Message;
dbCtx.SaveChanges();
return (DTOMaintenanceNoteModel)note;
}
public void DeleteNote(int noteId)
{
MaintenanceNoteModel note = FindNoteById(noteId);
dbCtx.MaintenancesNotes.Remove(note);
dbCtx.SaveChanges();
}
#endregion Notes
#region Attachment
public List<MaintenanceFileModel> FindAttachmentByMaintenance(int maintenanceId)
{
return dbCtx
.MaintenanceFiles
.Where(x => x.MaintenanceId == maintenanceId)
.ToList();
}
public MaintenanceFileModel FindAttachmentById(int attachmentId)
{
return dbCtx
.MaintenanceFiles
.Where(x => x.AttachmentId == attachmentId)
.FirstOrDefault();
}
public MaintenanceFileModel AddAttachment(string fileName, string localFileName, int maintenanceId, int userId)
{
MaintenanceFileModel file = new MaintenanceFileModel()
{
FileName = fileName,
LocalFileName = localFileName,
MaintenanceId = maintenanceId,
UserId = userId
};
// Add to db
dbCtx.MaintenanceFiles.Add(file);
dbCtx.SaveChanges();
return file;
}
public void DeleteAttachment(int attachmentId)
{
MaintenanceFileModel file = dbCtx.MaintenanceFiles.Where(x => x.AttachmentId == attachmentId).FirstOrDefault();
if (file != null)
{
dbCtx.MaintenanceFiles.Remove(file);
dbCtx.SaveChanges();
}
}
public void DeleteAttachment(MaintenanceFileModel attachment)
{
dbCtx.MaintenanceFiles.Remove(attachment);
dbCtx.SaveChanges();
if (File.Exists(MAINTENANCE_ATTACHMENT_PATH + attachment.LocalFileName))
File.Delete(MAINTENANCE_ATTACHMENT_PATH + attachment.LocalFileName);
}
#endregion Attachment
public bool CheckPassword(string password, string machineNumber, uint plcCounter, out int cw)
{
cw = -1;
SupportFunctions.ConvertStringMachineNumberIntoNumber(machineNumber, out bool containsLetters, out int intMachineVal);
if (!GetDataFromMaintenancePassword(password, containsLetters, out int pwdMachineNumber, out int pwdHours, out cw))
return false;
// Check machine number
if(intMachineVal == pwdMachineNumber)
{
// Convert plcCounter in hours and check if password is expired
if(((plcCounter/3600) - pwdHours) <= 50)
{
return true; // Ok
}
}
return false; // Invalid Password
}
private bool GetDataFromMaintenancePassword(string password, bool containsLetters, out int number, out int hours, out int cw)
{
number = -1;
hours = -1;
cw = -1;
if (String.IsNullOrEmpty(password))
return false;
string tmpPassword1 = "",
tmpPassword3 = "",
tmpPassword4 = "",
tmpPassword5 = "";
Hashtable htCifrario = new Hashtable
{
{ 'K', "0" },
{ 'M', "1" },
{ 'X', "2" },
{ 'N', "3" },
{ 'G', "4" },
{ 'V', "5" },
{ 'P', "6" },
{ 'Z', "7" },
{ 'H', "8" },
{ 'Q', "9" }
};
// Create tmpPassword5 changing characters that matches with characters in the hashtable
foreach (char c in password)
{
if (htCifrario.ContainsKey(c))
tmpPassword5 += htCifrario[c].ToString(); // Change character with hashtable val
else
tmpPassword5 += c;
}
// Get control number
var stringCw = Right(tmpPassword5, 1);
if (!int.TryParse(stringCw, out int controlNumber))
return false;
tmpPassword4 = tmpPassword5.Remove(tmpPassword5.Length - 1);
// Create tmpPassoword3
foreach(char c in tmpPassword4)
{
// If tmpPassword is empty copy the first character
if(tmpPassword3.Length == 0)
{
tmpPassword3 = c.ToString();
}
else
{
// Check if character is a number
if (char.IsNumber(c))
// Add first digit of -> Number + 10 - control number
tmpPassword3 += Right((char.GetNumericValue(c) + 10 - controlNumber).ToString(), 1);
else
tmpPassword3 += c.ToString();
}
}
if (containsLetters)
{
tmpPassword1 = tmpPassword3.PadLeft(15, '0');
number = Convert.ToInt32(tmpPassword1.Substring(5, 8), 16); // Convert from hexadecimal
cw = Convert.ToInt32(tmpPassword1.Substring(13, 2), 16); // Convert from hexadecimal
}
else
{
tmpPassword1 = tmpPassword3.PadLeft(11, '0');
number = Convert.ToInt32(tmpPassword1.Substring(5, 4), 16); // Convert from hexadecimal
cw = Convert.ToInt32(tmpPassword1.Substring(9, 2), 16); // Convert from hexadecimal
}
hours = Convert.ToInt32(tmpPassword1.Substring(0, 5), 16); // Convert from hexadecimal
return true;
}
private static string Right(string value, int size)
{
// if length is greater than "size" resets "size"
size = (value.Length < size ? value.Length : size);
// Substring is the equivalent of VB NET RIGHT
string newValue = value.Substring(value.Length - size);
return newValue;
}
}
}
@@ -0,0 +1,709 @@
using Step.Model.DatabaseModels;
using Step.Model.DTOModels.ToolModels;
using Step.Utils;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using static Step.Utils.SupportFunctions;
using static Step.Model.Constants;
namespace Step.Database.Controllers
{
public class NcToolManagerController : IDisposable
{
public DatabaseContext dbCtx;
public NcToolManagerController()
{
// Initialize database context
dbCtx = new DatabaseContext();
}
public void Dispose()
{
// Clear database context
dbCtx.Dispose();
}
public List<DbNcFamilyModel> FindFamilies()
{
List<DbNcFamilyModel> families = dbCtx
.Families
.Include("Tools")
.ToList();
return families;
}
public List<DTONcFamilyModel> GetFamilies()
{
List<DbNcFamilyModel> dbFamilies = FindFamilies();
return dbFamilies
.Select(x => (DTONcFamilyModel)x)
.ToList();
}
public List<DbNcFamilyModel> FindFamiliesByShankId(int shankId)
{
DbNcShankModel shank = FindShankWithTools(shankId);
// Get only families id
short[] ids = shank.Tools.Select(x => x.FamilyId).ToArray();
return FindFamilies() // Get Families
.Where(x => ids.Contains(x.FamilyId)) // Filter by ids
.ToList();
}
public DbNcToolModel FindTool(int toolId)
{
return dbCtx.Tools
.Where(x => x.ToolId == toolId)
.FirstOrDefault();
}
public DbNcToolModel FindToolWithDependencies(int toolId)
{
return dbCtx.Tools
.Where(x => x.ToolId == toolId)
.Include("Family")
.Include("Shank")
.FirstOrDefault();
}
public DbNcShankModel FindShankWithTools(int shankId)
{
return dbCtx.Shanks
.Include("Tools")
.Where(x => x.ShankId == shankId)
.FirstOrDefault();
}
public DbNcFamilyModel FindFamily(int familyId)
{
return dbCtx
.Families
.Where(x => x.FamilyId == familyId)
.Include("Tools")
.FirstOrDefault();
}
public List<DbNcToolModel> FindToolsWithDependencies()
{
List<DbNcToolModel> tools = dbCtx
.Tools
.Include("Family")
.Include("Shank")
.ToList();
return tools;
}
public List<DbNcToolModel> FindToolsByShankIdWithDependencies(int shankId)
{
List<DbNcToolModel> tools = FindToolsWithDependencies()
.Where(x => x.ShankId == shankId)
.ToList();
return tools;
}
public List<DbNcToolModel> FindTools()
{
List<DbNcToolModel> tools = dbCtx
.Tools
.ToList();
return tools;
}
public List<DTONcToolModel> GetTools()
{
List<DbNcToolModel> dbTools = FindToolsWithDependencies();
return dbTools
.Select(x => (DTONcToolModel)x)
.ToList();
}
public List<DbNcShankModel> FindShanks()
{
List<DbNcShankModel> shanks = dbCtx
.Shanks
.Include("MagazinePosition")
.ToList();
return shanks;
}
public DbNcShankModel FindShank(int shankId)
{
return dbCtx.Shanks
.Where(x => x.ShankId == shankId)
.FirstOrDefault();
}
public DbNcShankModel FindShanksByPositions(int magazineId, int positionId)
{
DbNcShankModel shank = FindShanks()
.Where(x => x.MagazineId == magazineId && x.PositionId == positionId)
.FirstOrDefault();
return shank;
}
public List<DbNcShankModel> FindShanksByFamilyId(int familyId)
{
return dbCtx
.Tools
.Include("Shank")
.Where(x => x.FamilyId == familyId && x.ShankId != null)
.Select(x => x.Shank)
.ToList();
}
public DbNcShankModel FindShankByToolId(int toolId)
{
return dbCtx
.Tools
.Include("Shank")
.Where(x => x.ToolId == toolId && x.ShankId != null)
.Select(x => x.Shank)
.FirstOrDefault();
}
public List<DTONcShankModel> GetShanks()
{
// Get shank from database
List<DbNcShankModel> dbShanks = dbCtx
.Shanks
.Include("Tools")
.ToList();
// Populate dto shanks
List<DTONcShankModel> dtoShanks = dbShanks
.Select(x => (DTONcShankModel)x)
.ToList();
return dtoShanks;
}
public List<DTONcShankModel> GetShanksWithSpace()
{
// Populate nks
List<DTONcShankModel> dtoShanks = GetShanks();
List<DTONcFamilyModel> dtoFamilies = GetFamilies();
// Calculate & set space occupied for each shank
foreach(var shank in dtoShanks)
{
// Get only families id
short[] ids = shank.ChildsTools.Select(x => x.FamilyId).ToArray();
// Get Families data
List<DTONcFamilyModel> families = dtoFamilies
.Where(x => ids.Contains(x.Id))
.ToList();
if (families.Count() > 0)
{
// Find max between families
shank.MaxRight = families.Max(x => x.RightSize);
shank.MaxLeft = families.Max(x => x.LeftSize);
}
}
return dtoShanks;
}
public DTONcShankModel GetShank(int shankId)
{
// Get shank from database
DTONcShankModel dtoShanks = GetShanksWithSpace()
.Where(x => x.Id == shankId)
.FirstOrDefault();
return dtoShanks;
}
public List<DbNcMagazinePositionModel> FindMagazinesPositions()
{
List<DbNcMagazinePositionModel> positions = dbCtx
.MagazinePositions
.ToList();
return positions;
}
public List<DbNcMagazinePositionModel> FindMagazinePositions(byte magId)
{
return dbCtx
.MagazinePositions
.Where(x => x.MagazineId == magId)
.ToList();
}
public void GetShankMaxSpaceOccupied(int shankId, out int maxRight, out int maxLeft)
{
// Get families
List<DbNcFamilyModel> families = FindFamiliesByShankId(shankId);
// Find max
maxRight = families.Max(x => x.RightSize);
maxLeft = families.Max(x => x.LeftSize);
}
public List<DTONcMagazinePositionModel> GetMagazinePositions(byte magId)
{
// Get only magazine positions that match with magazineId
List<DTONcMagazinePositionModel> magPos = FindMagazinePositions(magId).Select(x => (DTONcMagazinePositionModel)x).ToList();
// Get&filter shanks by magazineId in order to get only mounted shanks in the current magazineId
List<DbNcShankModel> shanks = dbCtx.Shanks.Where(x => x.MagazineId == magId || x.OriginMagazineId == magId).ToList();
foreach(DbNcShankModel shank in shanks)
{
DTONcMagazinePositionModel pos = null;
// Populate magazinePosition shank Id, check actual position and origin position
if(shank.MagazineId == magId)
pos = magPos // Actual case
.FirstOrDefault(x => x.PositionId == shank.PositionId);
else
pos = magPos // Origin case
.FirstOrDefault(x => x.PositionId == shank.OriginPositionId);
if (pos != null)
pos.ShankId = shank.ShankId;
}
// Convert in DTOModel and return
return magPos;
}
public DbNcMagazinePositionModel FindMagazinePosition(byte magId, ushort posId)
{
DbNcMagazinePositionModel positions = dbCtx
.MagazinePositions
.FirstOrDefault(x => x.MagazineId == magId && x.PositionId == posId);
return positions;
}
public List<DTONcShankModel> GetMountedShanks(int magazineId)
{
List<DTONcShankModel> dtoShanks = GetShanksWithSpace()
.Where(x =>
(x.MagazineId != null && x.MagazineId == magazineId) ||
(x.OriginMagazineId != null && x.OriginMagazineId == magazineId))
.ToList();
return dtoShanks;
}
public List<DbNcToolModel> GetMountedTools()
{
List<DbNcToolModel> tools = FindToolsWithDependencies()
.Where(x => x.Shank != null && x.Shank.MagazineId != null)
.ToList();
return tools;
}
public List<DTONcShankModel> GetAvailableShanksWithChilds()
{
List<DTONcShankModel> dtoShanks = GetShanksWithSpace()
.Where(x => x.MagazineId == null && x.ChildsTools.Count > 0)
.ToList();
return dtoShanks;
}
public List<DTONcToolModel> GetAvailableTools()
{
List<DTONcToolModel> dtoTools = GetTools()
.Where(x => x.ShankId == null || x.ShankId == 0)
.ToList();
return dtoTools;
}
public DbNcToolModel AddTool(DTONewNcToolModel dtoTool, short toolId)
{
// Copy data
DbNcToolModel dbTool = (DbNcToolModel)dtoTool;
if (toolId == 0)
// Get next id
dbTool.ToolId = GetFirstFreeId(dbCtx.Tools.Select(x => x.ToolId).ToList());
else
dbTool.ToolId = toolId;
dbCtx.Tools.Add(dbTool);
dbCtx.SaveChanges();
// Get foreign key data
dbCtx.Entry(dbTool).Reference(x => x.Family).Load();
dbCtx.Entry(dbTool).Reference(x => x.Shank).Load();
return dbTool;
}
public DbNcToolModel UpdateTool(int toolId, DTONewNcToolModel dtoTool)
{
DbNcToolModel tool = FindTool(toolId);
tool.Status = ((DbNcToolModel)dtoTool).Status;
var shankId = tool.ShankId;
// Update db model
SupportFunctions.CopyProperties(dtoTool, tool);
tool.ShankId = shankId;
// Save
dbCtx.SaveChanges();
return tool;
}
public DbNcToolModel UpdateToolOffset(int toolId, int position, short offsetId)
{
DbNcToolModel tool = FindTool(toolId);
switch (position)
{
case 1:
tool.OffsetId1 = offsetId;
break;
case 2:
tool.OffsetId2 = offsetId;
break;
case 3:
tool.OffsetId3 = offsetId;
break;
}
// Save
dbCtx.SaveChanges();
return tool;
}
public void DeleteTool(int toolId)
{
DbNcToolModel tool = FindTool(toolId);
if(tool != null)
DeleteTool(tool);
}
public void DeleteTool(DbNcToolModel tool)
{
dbCtx.Tools.Remove(tool);
dbCtx.SaveChanges();
}
public DbNcFamilyModel AddFamily(DTONcFamilyModel family)
{
DbNcFamilyModel dbFamily = (DbNcFamilyModel)family;
// Get next free id if id is 0
if (dbFamily.FamilyId == 0)
dbFamily.FamilyId = GetFirstFreeId(dbCtx.Families.Select(x => x.FamilyId).ToList());
dbFamily.Name = DEFAULT_FAM_NAME + dbFamily.FamilyId;
dbCtx.Families.Add(dbFamily);
dbCtx.SaveChanges();
return dbFamily;
}
public DbNcFamilyModel UpdateFamily(int familyId, DTONewNcFamilyModel family)
{
DbNcFamilyModel dbFamily = FindFamily(familyId);
// Copy data from NewModel to DbModel
SupportFunctions.CopyProperties(family, dbFamily);
// Set cooling byte
dbFamily.CoolingByte = ((DbNcFamilyModel)family).CoolingByte;
dbCtx.SaveChanges();
// Connect tools data
dbCtx.Entry(dbFamily).Collection(x => x.Tools).Load();
return dbFamily;
}
public void DeleteFamily(int famId)
{
var family = FindFamily(famId);
dbCtx.Families.Remove(family);
dbCtx.SaveChanges();
}
public DbNcShankModel AddShank(DTONewNcShankModel shank, short shankId = 0)
{
DbNcShankModel dbShank = (DbNcShankModel)shank;
if (shankId == 0)
// Get next id
dbShank.ShankId = GetFirstFreeId(dbCtx.Shanks.Select(x => x.ShankId).ToList());
else
dbShank.ShankId = shankId;
dbCtx.Shanks.Add(dbShank);
dbCtx.SaveChanges();
return dbShank;
}
public DbNcShankModel UpdateShank(int shankId, DTONewNcShankModel dtoShank)
{
DbNcShankModel ncShank = FindShankWithTools(shankId);
return UpdateShank(ncShank, dtoShank);
}
public DbNcShankModel UpdateShank(DbNcShankModel dbShank, DTONewNcShankModel dtoShank)
{
dbShank.Balluf = dtoShank.Balluf;
dbShank.MagazinePositionType = dtoShank.MagazinePositionType;
dbCtx.SaveChanges();
dbCtx.Entry(dbShank).Collection(x => x.Tools).Load();
return dbShank;
}
public DbNcShankModel DeleteNcShank(int shankId)
{
DbNcShankModel shank = FindShankWithTools(shankId);
DeleteNcShank(shank);
return shank;
}
public void DeleteNcShank(DbNcShankModel shank)
{
dbCtx.Shanks.Remove(shank);
dbCtx.SaveChanges();
}
public DbNcMagazinePositionModel UpdatePosition(DbNcMagazinePositionModel dbPos, DTONcMagazinePositionModel dtoPos)
{
dbCtx.MagazinePositions.Attach(dbPos);
dbPos.Type = dtoPos.Type;
dbPos.Disabled = dtoPos.Disabled;
dbCtx.SaveChanges();
return dbPos;
}
public DbNcMagazinePositionModel LoadShankInMagazine(byte magazineId, ushort positionId, DbNcShankModel shank)
{
dbCtx.Shanks.Attach(shank);
// Set ids with new positions
shank.MagazineId = magazineId;
shank.PositionId = positionId;
// Set original Ids
shank.OriginMagazineId = magazineId;
shank.OriginPositionId = positionId;
dbCtx.SaveChanges();
return FindMagazinePosition(magazineId, positionId);
}
public DbNcMagazinePositionModel LoadShankInMagazineWithoutOrigin(byte magazineId, ushort positionId, DbNcShankModel shank)
{
dbCtx.Shanks.Attach(shank);
// Set ids with new positions
shank.MagazineId = magazineId;
shank.PositionId = positionId;
dbCtx.SaveChanges();
return FindMagazinePosition(magazineId, positionId);
}
public DbNcMagazinePositionModel UnloadShankInMagazine(byte magazineId, ushort positionId, DbNcShankModel shank)
{
dbCtx.Shanks.Attach(shank);
// set id to null
shank.MagazineId = null;
shank.PositionId = null;
shank.OriginMagazineId = null;
shank.OriginPositionId = null;
dbCtx.SaveChanges();
return FindMagazinePosition(magazineId, positionId);
}
public DTONcShankModel LoadToolIntoShank(DbNcToolModel tool, short shankId)
{
dbCtx.Tools.Attach(tool);
// Set tool shankId
tool.ShankId = shankId;
dbCtx.SaveChanges();
return GetShank(shankId);
}
public DTONcShankModel UnloadToolFromShank(DbNcToolModel tool)
{
dbCtx.Tools.Attach(tool);
int? shankId = tool.ShankId;
// Set to null shankId
tool.ShankId = null;
dbCtx.SaveChanges();
return GetShank(shankId.Value);
}
public void SetupMagazinePositions(List<DbNcMagazinePositionModel> config)
{
dbCtx.MagazinePositions.AddRange(config);
dbCtx.SaveChanges();
}
public void UpdateToolsData(List<DbNcToolModel> tools)
{
foreach (var tool in tools)
{
DbNcToolModel tmpTool = dbCtx.Tools.Where(x => x.ToolId == tool.ToolId).FirstOrDefault();
tmpTool = tool;
}
dbCtx.SaveChanges();
}
public DTOExportToolTableModel GetExportData()
{
return new DTOExportToolTableModel
{
Tools = FindTools(),
Families = FindFamilies(),
Shanks = FindShanks()
.Select(x => {
// Reset positional Data
x.MagazineId = null;
x.PositionId = null;
x.OriginMagazineId = null;
x.OriginPositionId = null;
return x; })
.ToList()
};
}
public List<DTOImportStatusModel> ImportData(DTOExportToolTableModel data)
{
List<DTOImportStatusModel> importStatus = new List<DTOImportStatusModel>();
List<DbNcToolModel> tools = FindTools();
List<DbNcFamilyModel> families = FindFamilies();
List<DbNcShankModel> shanks = FindShanks();
var positions = FindMagazinesPositions();
if (positions.Count() == 0)
return new List<DTOImportStatusModel>();
if(data.Families != null)
// loop thought new families
foreach (var family in data.Families)
{
// Check if not exist
if (families.FirstOrDefault(x => x.FamilyId == family.FamilyId) == null)
{
dbCtx.Families.Add(family);
// Set status
importStatus.Add(new DTOImportStatusModel()
{
Id = family.FamilyId,
Status = IMPORT_STATUS.OK.ToString(),
Type = "FAMILY"
});
}
else
{
// Set duplicated status
importStatus.Add(new DTOImportStatusModel()
{
Id = family.FamilyId,
Status = IMPORT_STATUS.EXIST.ToString(),
Type = "FAMILY"
});
}
}
if(data.Shanks != null)
// loop thought new shanks
foreach (var shank in data.Shanks)
{
// Check if not exist
if (shanks.FirstOrDefault(x => x.ShankId == shank.ShankId) == null)
{
dbCtx.Shanks.Add(shank);
importStatus.Add(new DTOImportStatusModel()
{
Id = shank.ShankId,
Status = IMPORT_STATUS.OK.ToString(),
Type = "SHANK"
});
}
else
{
importStatus.Add(new DTOImportStatusModel()
{
Id = shank.ShankId,
Status = IMPORT_STATUS.EXIST.ToString(),
Type = "SHANK"
});
}
}
if(data.Tools != null)
// loop thought new tools
foreach (var tool in data.Tools)
{
// Check if not exist
if (tools.FirstOrDefault(x => x.ToolId == tool.ToolId) == null)
{
dbCtx.Tools.Add(tool);
importStatus.Add(new DTOImportStatusModel()
{
Id = tool.ToolId,
Status = IMPORT_STATUS.EXIST.ToString(),
Type = "TOOL"
});
}
else
{
importStatus.Add(new DTOImportStatusModel()
{
Id = tool.ToolId,
Status = IMPORT_STATUS.EXIST.ToString(),
Type = "TOOL"
});
}
}
// Save
dbCtx.SaveChanges();
return importStatus;
}
}
}
@@ -0,0 +1,124 @@
using Step.Model.DatabaseModels;
using Step.Model.DTOModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Step.Model.Constants;
namespace Step.Database.Controllers
{
public class QueueController : IDisposable
{
private DatabaseContext dbCtx;
public static Dictionary<int, List<DTOQueueModel>> PartProgramQueue = new Dictionary<int, List<DTOQueueModel>>();
public static Dictionary<int, int> QueueRunningIndexes = new Dictionary<int, int>();
public QueueController()
{
// Initialize database context
dbCtx = new DatabaseContext();
}
public void Dispose()
{
// Clear database context
dbCtx.Dispose();
}
public void UpdateQueue()
{
dbCtx.Queue.RemoveRange(dbCtx.Queue);
var dbRows = new List<QueueItemsModel>();
foreach (var item in PartProgramQueue)
{
// Create database model
dbRows =item.Value.Select(x => new QueueItemsModel()
{
Id = x.Id,
AbsolutePath = x.AbsolutePath,
PartProgramName = x.PartProgramName,
Process = item.Key, // Process
Reps = x.Reps,
RemainingReps = x.RemainingReps,
Status = (int)x.Status
}).ToList();
// Add to db
dbCtx.Queue.AddRange(dbRows);
}
dbCtx.SaveChanges();
}
public void UpdateReps(int processId, int id, int reps)
{
QueueItemsModel item = dbCtx.Queue.FirstOrDefault(x => x.Id == id && x.Process == processId);
if (item == null)
return;
// Update reps
item.Reps = reps;
item.RemainingReps = reps;
dbCtx.SaveChanges();
}
public void DeleteItem(int processId, int id)
{
QueueItemsModel item = dbCtx.Queue.FirstOrDefault(x => x.Id == id && x.Process == processId);
if(item == null)
return;
dbCtx.Queue.Remove(item);
dbCtx.SaveChanges();
}
public void ReadAndPopulateQueue()
{
var dbQueue = dbCtx.Queue.ToList();
bool foundData = false;
foreach(var entity in dbQueue)
{
// Check if process queue exists
if (!PartProgramQueue.ContainsKey(entity.Process))
PartProgramQueue.Add(entity.Process, new List<DTOQueueModel>());
// Add db row to queue
PartProgramQueue[entity.Process].Add(new DTOQueueModel()
{
Id = entity.Id,
AbsolutePath = entity.AbsolutePath,
PartProgramName = entity.PartProgramName,
Reps = entity.Reps,
RemainingReps = entity.RemainingReps,
Status = (QUEUE_ITEM_STATUS)entity.Status
});
if ((QUEUE_ITEM_STATUS)entity.Status != QUEUE_ITEM_STATUS.FINISHED && !foundData)
{
QueueRunningIndexes[entity.Process] = entity.Id - 1;
foundData = true;
}
if ((QUEUE_ITEM_STATUS)entity.Status == QUEUE_ITEM_STATUS.RUNNING)
QueueRunningIndexes[entity.Process] = entity.Id - 1;
}
}
public void UpdateQueueIdsAndSave(int processId)
{
// Fix new ids
for (int i = 0; i < PartProgramQueue[processId].Count(); i++)
PartProgramQueue[processId][i].Id = i + 1;
UpdateQueue();
}
}
}
@@ -0,0 +1,140 @@
using Step.Database.Redis;
using Step.Model.DTOModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Step.Database.Controllers
{
public static class RedisController
{
private const string redisNotificationAddress = "Machine:ProductionProcesses:%NN%:Notification";
private const string redisProdNameAddress = "Machine:ProductionProcesses:%NN%:Name";
private const string redisRepsTargetAddress = "Machine:ProductionProcesses:%NN%:Programs:01:RepsTarget";
private const string redisRepsDoneAddress = "Machine:ProductionProcesses:%NN%:Programs:01:RepsDone";
private const string redisAlmCurr = "AdpConf:Plc:Condition:Curr";
private const string redisAlmIt = "AdpConf:Plc:Condition:It";
private const string redisAlmEn = "AdpConf:Plc:Condition:En";
private const string startTimestamp = "Machine:ProductionProcesses:%NN%:Programs:01:StartTime";
private const string endTimestamp = "Machine:ProductionProcesses:%NN%:Programs:01:EndTime";
private const string notification = "Machine:ProductionProcesses:%NN%:Notification";
private const string partIdPath = "Machine:ProductionProcesses:%NN%:Programs:01:PartId";
private const string maintenanceTitlePath = "Machine:Maintenences:%NN%:Title";
private const string maintenanceCompletionPath = "Machine:Maintenences:%NN%:Completion";
private const string maintenanceDescriptionPath = "Machine:Maintenences:%NN%:Description";
private const string currentUserPath = "Machine:Hmi:User";
private const string toolNamePath = "Machine:OperatingGroups:%NN%:ToolName";
private const string machineMessagePath = "Machine:Messages";
public static void WriteProductionNotification(uint ProductionProcess, string Notification)
{
string redisHash = redUtil.man.redHash(redisNotificationAddress).Replace("%NN%", ProductionProcess.ToString("00"));
redUtil.man.setRSV(redisHash, Notification);
}
public static void WriteProductionName(uint ProductionProcess, string Name)
{
string redisHash = redUtil.man.redHash(redisProdNameAddress).Replace("%NN%", ProductionProcess.ToString("00"));
redUtil.man.setRSV(redisHash, Name);
}
public static void WriteProductionRepsTarget(uint ProductionProcess, string RepsTarget)
{
string redisHash = redUtil.man.redHash(redisRepsTargetAddress).Replace("%NN%", ProductionProcess.ToString("00"));
redUtil.man.setRSV(redisHash, RepsTarget);
}
public static void WriteProductionRepsDone(uint ProductionProcess, string RepsDone)
{
string redisHash = redUtil.man.redHash(redisRepsDoneAddress).Replace("%NN%", ProductionProcess.ToString("00"));
redUtil.man.setRSV(redisHash, RepsDone);
}
public static bool WriteAlarmsConfigCurr(Dictionary<string, string> alarms)
{
string redisHash = redUtil.man.redHash(redisAlmCurr);
return redUtil.man.redSaveHashDict(redisHash, alarms);
}
public static bool WriteAlarmsConfigEn(Dictionary<string, string> alarms)
{
string redisHash = redUtil.man.redHash(redisAlmEn);
return redUtil.man.redSaveHashDict(redisHash, alarms);
}
public static bool WriteAlarmsConfigIt(Dictionary<string, string> alarms)
{
string redisHash = redUtil.man.redHash(redisAlmIt);
return redUtil.man.redSaveHashDict(redisHash, alarms);
}
public static bool WriteStartProgram(uint process)
{
string redisHash = redUtil.man.redHash(startTimestamp).Replace("%NN%", process.ToString("00"));
return redUtil.man.setRSV(redisHash, DateTime.Now.ToString());
}
public static bool WriteEndProgram(uint process)
{
string redisHash = redUtil.man.redHash(endTimestamp).Replace("%NN%", process.ToString("00"));
return redUtil.man.setRSV(redisHash, DateTime.Now.ToString());
}
public static bool WriteNotification(uint process, string textNotification)
{
string redisHash = redUtil.man.redHash(notification).Replace("%NN%", process.ToString("00"));
return redUtil.man.setRSV(redisHash, textNotification);
}
public static bool WritePartId(uint process, string partId)
{
string redisHash = redUtil.man.redHash(partIdPath).Replace("%NN%", process.ToString("00"));
return redUtil.man.setRSV(redisHash, partId);
}
public static bool WriteMaintenance(int maintenanceId, string maintenanceTitle, int maintenanceCompleition, string maintenanceDescription)
{
string redisHash = redUtil.man.redHash(maintenanceTitlePath).Replace("%NN%", maintenanceId.ToString());
var status = redUtil.man.setRSV(redisHash, maintenanceTitle);
if (!status)
return status;
redisHash = redUtil.man.redHash(maintenanceCompletionPath).Replace("%NN%", maintenanceId.ToString());
status = redUtil.man.setRSV(redisHash, maintenanceCompleition.ToString());
if (!status)
return status;
redisHash = redUtil.man.redHash(maintenanceDescriptionPath).Replace("%NN%", maintenanceId.ToString());
return redUtil.man.setRSV(redisHash, maintenanceDescription);
}
public static bool WriteCurrentUser(int userId)
{
string redisHash = redUtil.man.redHash(currentUserPath);
return redUtil.man.setRSV(redisHash, userId.ToString());
}
public static bool WriteToolName(int spindleId, string toolName)
{
string redisHash = redUtil.man.redHash(toolNamePath).Replace("%NN%", spindleId.ToString("00"));
return redUtil.man.setRSV(redisHash, toolName);
}
public static bool SendMessage(DTOMessageModel message)
{
string redisHash = redUtil.man.redHash(machineMessagePath);
return redUtil.man.setJson(redisHash, message);
}
}
}
@@ -0,0 +1,84 @@
using Step.Model.DatabaseModels;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Step.Database.Controllers
{
public class SessionsController : IDisposable
{
private DatabaseContext dbCtx;
public SessionsController()
{
// Initialize database context
dbCtx = new DatabaseContext();
}
public void Dispose()
{
// Clear database context
dbCtx.Dispose();
}
public SessionModel FindSessionByToken(string token)
{
return dbCtx
.Sessions
.Include("MachineUser")
.Where(x => x.Token == token) // Find session by token
.FirstOrDefault();
}
public List<MachineUserModel> FindMachineUserSession()
{
return dbCtx
.Sessions
.Include("MachineUser")
.Select(x => x.MachineUser)
.GroupBy(x => x.MachineUserId)
.Select(x => x.FirstOrDefault())
.ToList();
}
public void DeleteUserSessions(int machineUserId)
{
dbCtx
.Sessions
.RemoveRange( // Delete rows
dbCtx
.Sessions
.Where(x => x.MachineUserId == machineUserId) // Find all the session with matching machineUserId
);
// Commit changes
dbCtx.SaveChanges();
}
public void DeleteSessionsByUserAndMachineId(int machineId, int userId)
{
MachineUserModel machineUser = null;
using (MachinesUsersController machinesUsersController = new MachinesUsersController())
{
// Find machine_user id
machineUser = machinesUsersController.FindByUserId(machineId, userId);
}
DeleteUserSessions(machineUser.MachineUserId);
}
public void Create(int machineUserId, string token)
{
// Create session model
SessionModel session = new SessionModel()
{
MachineUserId = machineUserId,
Token = token,
FirstLogin = DateTime.Now
};
// Add to database
dbCtx.Sessions.Add(session);
// Commit changes
dbCtx.SaveChanges();
}
}
}
@@ -0,0 +1,113 @@
using Step.Model.DatabaseModels;
using Step.Model.DTOModels;
using System;
using System.Collections.Generic;
using System.Linq;
using static Step.Model.Constants;
using static Step.Config.ServerConfig;
namespace Step.Database.Controllers
{
public class UserSoftkeysController : IDisposable
{
private DatabaseContext dbCtx;
public UserSoftkeysController()
{
// Initialize database context
dbCtx = new DatabaseContext();
}
public void Dispose()
{
// Clear database context
dbCtx.Dispose();
}
public List<DTOUserSoftKeyConfigModel> GetUserSoftkeyConfig()
{
List<DTOUserSoftKeyConfigModel> config = new List<DTOUserSoftKeyConfigModel>();
foreach (var softKey in SoftKeysConfig)
{
// Create subkeys dictionary for group
Dictionary<int, string> tmpSubKey = new Dictionary<int, string>();
if (softKey.Type == SOFTKEY_TYPE.GROUP && softKey.SubKeys != null)
{
tmpSubKey = new Dictionary<int, string>();
foreach (var subKey in softKey.SubKeys)
{
tmpSubKey.Add(subKey.Id, subKey.Text);
}
}
// Add to the category the new softkey
config.Add(new DTOUserSoftKeyConfigModel()
{
Id = softKey.Id,
Category = softKey.Category,
OperatorConfirmationNeeded = softKey.OperatorConfirmationNeeded,
Type = softKey.Type,
SubKeys = tmpSubKey
});
}
return config;
}
public List<FavoriteUserSoftkeyModel> FindUserFavoriteSoftkeys(int userId)
{
return dbCtx.
FavoriteUserSoftkeys
.Where(x => x.UserId == userId)
.ToList();
}
public List<DTOUserSoftKeyConfigModel> GetUserFavoriteSoftkeys(int userId)
{
// Find user softkey stored in the database
List<FavoriteUserSoftkeyModel> favoriteKey = FindUserFavoriteSoftkeys(userId);
// Get config
List<DTOUserSoftKeyConfigModel> userSoftkey = GetUserSoftkeyConfig();
return userSoftkey
.Where(x =>
favoriteKey.Any(y => y.SoftkeyId == x.Id
))
.ToList();
}
public List<DTOUserSoftKeyConfigModel> InsertUserSoftkeyModel(List<uint> softKeyIds, int userId)
{
List<FavoriteUserSoftkeyModel> softKeys = new List<FavoriteUserSoftkeyModel>();
// Create new list with db models
foreach (int softKeyId in softKeyIds)
{
softKeys.Add(new FavoriteUserSoftkeyModel()
{
UserId = userId,
SoftkeyId = softKeyId
});
}
// Add list to database
dbCtx.FavoriteUserSoftkeys.AddRange(softKeys);
dbCtx.SaveChanges();
return GetUserFavoriteSoftkeys(userId);
}
public void DeleteUserSoftkeyModel(int userId)
{
// Get user favorite softkeys
List<FavoriteUserSoftkeyModel> softKeys = FindUserFavoriteSoftkeys(userId);
foreach (FavoriteUserSoftkeyModel sofkey in softKeys)
{
// Delete
dbCtx.FavoriteUserSoftkeys.Remove(sofkey);
}
// Save database context
dbCtx.SaveChanges();
}
}
}
@@ -0,0 +1,339 @@
using Step.Model.DatabaseModels;
using Step.Model.DTOModels;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Helpers;
using static Step.Config.ServerConfig;
using static Step.Model.Constants;
namespace Step.Database.Controllers
{
public class UsersController : IDisposable
{
private DatabaseContext dbCtx;
public UsersController()
{
// Initialize database context
dbCtx = new DatabaseContext();
}
public void Dispose()
{
// Clear database context
dbCtx.Dispose();
}
public DTOUserModel Create(string username, string password, string firstName, string lastName, CultureInfo language)
{
UserModel user = CreateUserModel(username, password, firstName, lastName, language);
// Add to database
dbCtx.Users.Add(user);
// Commit changes
dbCtx.SaveChanges();
using(MachinesUsersController machController = new MachinesUsersController())
{
machController.Create(MachineConfig.MachineId, user.UserId, 3);
}
return GetUserInfo(user.UserId);
}
public static UserModel CreateUserModel(int id, string username, string password, string firstName, string lastName, CultureInfo language)
{
// Create a new user model with params
return new UserModel()
{
UserId = id,
Username = username,
Password = Crypto.HashPassword(password),
FirstName = firstName,
LastName = lastName,
SecurityStamp = Guid.NewGuid().ToString(),
Language = language,
Email = "",
IsLocal = true,
CmsConnectUserId = ""
};
}
public static UserModel CreateUserModel(string username, string password, string firstName, string lastName, CultureInfo language)
{
return CreateUserModel(0, username, password, firstName, lastName, language);
}
public bool CreateCMSConnectUser(string username, string password, string firstName, string lastName, CultureInfo language, string email, string connectUserId, bool isAdmin)
{
var usr = FindByUsername(username);
// if user was already imported, activate
if(usr != null)
{
usr.Deleted = false;
dbCtx.SaveChanges();
return true;
}
UserModel user = CreateUserModel(username, password, firstName, lastName, language);
user.Email = email;
user.IsLocal = false;
user.CmsConnectUserId = connectUserId;
// Add to database
dbCtx.Users.Add(user);
// Commit changes
dbCtx.SaveChanges();
using (MachinesUsersController machController = new MachinesUsersController())
{
var role = ROLE_IDS.CUSTOMER_OPERATOR;
if (isAdmin)
role = ROLE_IDS.CUSTOMER_ADMIN;
machController.Create(MachineConfig.MachineId, user.UserId, (int)role);
}
return true;
}
public DTOUserModel GetUserInfo(int userId)
{
// Find user by Id with Role object included
UserModel userDatabaseModel = dbCtx.Users.Where(u => u.UserId == userId).FirstOrDefault();
if (userDatabaseModel == null)
return null;
DTORoleModel roleModel = null;
// Find user role through machineUser table
using (MachinesUsersController machinesUsersControler = new MachinesUsersController())
{
roleModel = machinesUsersControler.GetUserRoleData(MachineConfig.MachineId, userId);
if (roleModel == null)
return null;
}
return new DTOUserModel() // Return DTOUserModel
{
Id = userDatabaseModel.UserId,
Username = userDatabaseModel.Username,
FirstName = userDatabaseModel.FirstName,
LastName = userDatabaseModel.LastName,
Language = userDatabaseModel.Language,
Role = roleModel
};
}
public UserModel FindById(int id)
{
// Find user by Id with Role object included
return dbCtx.Users.Where(u => u.UserId == id).FirstOrDefault();
}
public UserModel FindByUsername(string username)
{
// Find user by Id with Role object included
return dbCtx.Users.Where(u => u.Username == username).FirstOrDefault();
}
public UserModel FindNotDeletedByUsername(string username)
{
// Find user by Id with Role object included
return dbCtx
.Users
.Where(u => u.Username == username && !u.Deleted)
.FirstOrDefault();
}
public UserModel FindByUsernameAndPassword(string username, string password)
{
// Find if username exists
UserModel user = FindByUsername(username);
if (user != null)
{
if (user.Deleted == true)
return null;
// Check if the passwords match
if (Crypto.VerifyHashedPassword(user.Password, password) != true)
{
return null;
}
}
return user;
}
public void CreateCmsDefaultUserIfNotExists(int machineId, string username, string password, string name, string lastname, CultureInfo info, ROLE_IDS roleId)
{
// Find if there is a cms standard user
UserModel user = FindByUsername(username);
if (user == null)
{
// If not exist add new user
user = dbCtx.Users.Add(
CreateUserModel(username, password, name, lastname, info)
);
// Commit changes
dbCtx.SaveChanges();
}
// Add user to local machine users if not exists
using (MachinesUsersController machinesUsersController = new MachinesUsersController())
{
MachineUserModel machineUser = machinesUsersController.FindByUserId(machineId, user.UserId);
if (machineUser == null)
machinesUsersController.Create(machineId, user.UserId, (int)roleId);
}
}
public void ChangeUserLanguage(int userId, CultureInfo newLanguage)
{
UserModel user = FindById(userId);
if (user != null)
{
user.Language = newLanguage;
dbCtx.SaveChanges();
}
}
public List<DTOMessageUserModel> GetMessageUserList()
{
using (MachinesUsersController machineController = new MachinesUsersController())
{
// Find user by Id with Role object included
var tmpUser = dbCtx
.Users
.Where(x => x.Deleted == false) // Get not deleted users
.Join( dbCtx.MachinesUsers,
u => u.UserId,
m => m.UserId,
(u, m) => new { Users = u, MachinesUsers = m }
)
.Where(x => x.MachinesUsers.Role.Level < MIN_CMS_ROLE)
.ToList();
return tmpUser
.Select(x => new DTOMessageUserModel() // Return DTOUserModel
{
Id = x.Users.UserId,
FirstName = x.Users.FirstName,
LastName = x.Users.LastName,
Username = x.Users.Username
})
.GroupBy(elem => elem.Id).Select(group => group.First())
.ToList();
}
}
#region User Manager
public List<DTOUserModel> GetUserList()
{
using (MachinesUsersController machineController = new MachinesUsersController())
{
// Find user by Id with Role object included
var tmpUser = dbCtx
.Users
.Where(x => x.Deleted == false) // Get not deleted users
.ToList();
return tmpUser
.Select(x => new DTOUserModel() // Return DTOUserModel
{
Id = x.UserId,
Username = x.Username,
FirstName = x.FirstName,
LastName = x.LastName,
Language = x.Language,
IsLocal = x.IsLocal,
Email = x.Email,
CmsConnectUserId = x.CmsConnectUserId,
Role = machineController.GetUserRoleData(MachineConfig.MachineId, x.UserId)
}).Where(
x=> x.Role.Level < MIN_CMS_ROLE)
.ToList();
}
}
public List<UserModel> GetCMSConnectUserList()
{
using (MachinesUsersController machineController = new MachinesUsersController())
{
// Find user by Id with Role object included
return dbCtx
.Users
.Where(x => x.IsLocal == false) // Get not deleted users
.ToList();
}
}
public DTOUserModel UpdateUserData(int userId, DTONewUserModel userData)
{
UserModel user = FindById(userId);
if (user != null)
{
user.FirstName = userData.FirstName;
user.LastName = userData.LastName;
user.Username = userData.Username;
dbCtx.SaveChanges();
}
return GetUserInfo(userId);
}
public DTOUserModel UpdateUserPassword(int userId, DTONewPasswordrModel userData)
{
UserModel user = FindById(userId);
if (user != null)
{
user.Password = Crypto.HashPassword(userData.newPassword);
dbCtx.SaveChanges();
}
return GetUserInfo(userId);
}
public bool isCMSRole(int roleId)
{
var tmpRole = dbCtx.Roles
.ToList()
.First(X => X.RoleId == roleId);
if (tmpRole == null)
return true;
else
return tmpRole.Level >= MIN_CMS_ROLE;
}
public DTOUserModel UpdateUserRole(int userId, int roleId)
{
using (MachinesUsersController machineController = new MachinesUsersController())
{
machineController.UpdateUserRole(MachineConfig.MachineId, userId, roleId);
}
return GetUserInfo(userId);
}
public void DeleteUser(UserModel user)
{
user.Deleted = true;
dbCtx.SaveChanges();
}
#endregion User Manager
}
}