using System;
using System.Collections.Generic;
using System.Linq;
using Thermo.Active.Model.DatabaseModels;
namespace Thermo.Active.Database.Controllers
{
public class ProdInfoController : IDisposable
{
private DatabaseContext dbCtx;
public ProdInfoController()
{
// Initialize database context
dbCtx = new DatabaseContext();
}
public void Dispose()
{
// Clear database context
dbCtx.Dispose();
}
///
/// Get record by NumDone
///
///
///
public ProdInfoModel FindByNumDone(int num)
{
return dbCtx
.ProdInfo
.Where(x => x.NumDone == num)
.SingleOrDefault();
}
///
/// Get historical paginated data from DB (DESC ordered
///
///
///
///
public List GetPaginated(int numStart, int numRecord)
{
// cehck numEnd
int numEnd = numStart - numRecord;
if (numEnd < 0)
numEnd = 0;
// retrieve
return dbCtx
.ProdInfo
.Where(x => x.NumDone <= numStart && x.NumDone > numEnd)
.OrderByDescending(x => x.DtEvent)
.ToList();
}
///
/// Create new prodInfo record on DB
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
public ProdInfoModel Create(short NumTarget, short NumDone, int TimeWarm, int TimeVent, int TimeVacuum, int TimeCycleGross, int TimeCycleNet, double MaterialTempEndWarm, double MaterialTempEndVent, double MoldTemp, double VacuumReadVal, double MouldEnergyOUT, double MouldEnergyIN)
{
// Create database machine model
ProdInfoModel prodData = new ProdInfoModel()
{
DtEvent = DateTime.UtcNow,
NumTarget = NumTarget,
NumDone = NumDone,
TimeWarm = TimeWarm,
TimeVent = TimeVent,
TimeVacuum = TimeVacuum,
TimeCycleGross = TimeCycleGross,
TimeCycleNet = TimeCycleNet,
MaterialTempEndWarm = MaterialTempEndWarm,
MaterialTempEndVent = MaterialTempEndVent,
MoldTemp = MoldTemp,
VacuumReadVal = VacuumReadVal,
MouldEnergyOUT = MouldEnergyOUT,
MouldEnergyIN = MouldEnergyIN
};
try
{
// Add to database
dbCtx.ProdInfo.Add(prodData);
// Commit changes
dbCtx.SaveChanges();
}
catch
{ }
return prodData;
}
///
/// Process table and keep only maxKeep most recent ones
///
///
///
public bool PurgeOldest(int maxKeep)
{
bool answ = false;
// check if purge needed
int numRec = dbCtx.ProdInfo.Count();
if (numRec > maxKeep)
{
ProdInfoModel firstToDelete = (ProdInfoModel)(from p in dbCtx.ProdInfo
orderby p.DtEvent descending
select p).Skip(maxKeep).Take(1);
// call deletion
dbCtx
.ProdInfo
.RemoveRange(
dbCtx
.ProdInfo
.Where(x => x.DtEvent <= firstToDelete.DtEvent)
);
try
{
// save!
dbCtx.SaveChanges();
answ = true;
}
catch
{ }
}
return answ;
}
///
/// Process table and delete all record (truncate)
///
///
public bool PurgeAll()
{
bool answ = false;
try
{
dbCtx
.Database
.ExecuteSqlCommand("TRUNCATE TABLE prodInfo");
}
catch
{ }
return answ;
}
}
}