EnVisageOnline/Main/Source/EnVisage/Code/ThreadedProcessing/BackgroundProcessManager.cs

733 lines
35 KiB
C#

using EnVisage.App_Start;
using EnVisage.Code.BLL;
using EnVisage.Code.Integration;
using EnVisage.Controllers;
using EnVisage.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Threading;
using System.Web.Hosting;
using NLog;
namespace EnVisage.Code.ThreadedProcessing
{
public class BackgroundProcessManager : IRegisteredObject
{
private CancellationToken cancellationToken;
private Guid TaskID;
private Guid UserID;
private EnVisageEntities DBContext;
private EnVisageEntities NotificationContext;
protected readonly Logger Logger = LogManager.GetCurrentClassLogger();
public void Stop(bool immediate)
{
}
public BackgroundProcessManager()
{
UserID = Guid.Empty;
TaskID = Guid.NewGuid();
}
public BackgroundProcessManager(Guid userid)
{
UserID = userid;
TaskID = Guid.NewGuid();
}
public BackgroundProcessManager(Guid taskId, Guid userid)
{
TaskID = taskId;
UserID = userid;
}
public BackgroundProcessManager(EnVisageEntities prevuEntity)
{
this.DBContext = prevuEntity;
}
public BackgroundProcessManager(EnVisageEntities prevuEntity, EnVisageEntities notificationEF)
{
this.DBContext= prevuEntity;
this.NotificationContext = notificationEF;
}
#region Non Project Time Import
public void BulkNonProjectTimeAsync(List<NonProjectTimeModel> apiModels, Guid savedId)
{
BackgroundProcess.RunJob(BulkNonProjectTime, apiModels, savedId);
}
public bool BulkNonProjectTime(List<NonProjectTimeModel> apiModels, Guid savedId,CancellationToken ct)
{
NonProjectTimeManager manager = new NonProjectTimeManager(this.DBContext);
//string processid = "ImportNonProjectTIme";
string message = "Non project time import/update started for " + apiModels.Count() + " Records";
this.TaskStarted(message);
var canceled = apiModels.Where(x => x.Details.ToLower().Trim() == "canceled").ToList();
var approved = apiModels.Where(x => x.Details.ToLower().Trim() == "approved").ToList();
foreach (NonProjectTimeModel m in canceled)
{
var ResourceId = m.Resources.FirstOrDefault();
var cancelAllocation = m.NonProjectTimeAllocations.FirstOrDefault();
var deleteNPTimeId=GetNonProjectTimeRecord(m);
if (deleteNPTimeId != Guid.Empty)
{
// Remove non-project time from DB
var command = string.Format("exec sp_DeleteNonProjectTime '{0}'", deleteNPTimeId);
((DBContext) as IObjectContextAdapter).ObjectContext.ExecuteStoreCommand(command);
}
var approvedRec = approved.Where(x => x.NonProjectTimeStartDate == m.NonProjectTimeStartDate );
foreach(NonProjectTimeModel a in approvedRec)
{
var aResource = a.Resources.FirstOrDefault();
var allocation = a.NonProjectTimeAllocations.FirstOrDefault();
if (aResource == ResourceId)
{
if (allocation.WeekEndingDate == cancelAllocation.WeekEndingDate &&
allocation.HoursOff == cancelAllocation.HoursOff && a.NonProjectTimeStartDate == m.NonProjectTimeStartDate
&& a.NonProjectTimeEndDate == m.NonProjectTimeEndDate)
approved.Remove(a);
}
}
}
foreach (NonProjectTimeModel m in approved)
{
var id = GetNonProjectTimeRecord(m);
if (id == Guid.Empty) {
manager.Save(m);
DBContext.SaveChanges();
}
}
return true;
}
private Guid GetNonProjectTimeRecord(NonProjectTimeModel m)
{
try
{
var allocationRec = m.NonProjectTimeAllocations.FirstOrDefault();
var delresourceid = m.Resources.FirstOrDefault();
var startDate = m.NonProjectTimeStartDate;
var endDate = m.NonProjectTimeEndDate;
var np2prs= DBContext.NonProjectTime2Resource.Where(x => x.PeopleResourceId == delresourceid).ToList();
var query = from npt in DBContext.NonProjectTimes
join npr in DBContext.NonProjectTime2Resource on npt.Id equals npr.NonProjectTimeId
join npa in DBContext.NonProjectTimeResourceAllocations on npr.Id equals npa.NonProjectTime2ResourceId
where npt.StartDate == startDate && npr.PeopleResourceId == delresourceid && npa.HoursOff == allocationRec.HoursOff
&& npa.WeekEndingDate == allocationRec.WeekEndingDate
&& npt.EndDate==endDate
select npt.Id;
Guid? id= query.FirstOrDefault();
if (id.HasValue)
return id.Value;
}
catch
{
}
return Guid.Empty;
}
#endregion
#region People Resource Updates
public bool BulkPeopleResourceRecordEdit(List<PeopleResourceAPIModel> apiModels, Guid saveID, CancellationToken ct)
{
string processid = "ImportPeopleResource";
string message = "People Resource import/update started for " + apiModels.Count() + " Records";
this.TaskStarted(message);
int exAdded = 0;
int excAdded = 0;
int crdtDepartmentAdded = 0;
int prAdded = 0;
int prSkipped = 0;
int prUpdatedCalc = 0;
int prUpdatedNoCalc = 0;
Guid TransactionID = Guid.NewGuid();
ImportDataController.LogHeaderMessage(processid, message, TransactionID);
foreach (PeopleResourceAPIModel apiModel in apiModels)
{
if (DBContext == null )
DBContext = new EnVisageEntities();
var userName = DBContext.AspNetUsers.Where(x => x.Id == UserID.ToString()).Select(x => x.UserName).FirstOrDefault();
try
{
// EnVisageEntities _dbContext = new EnVisageEntities();
PeopleResource prDbObj = DBContext.PeopleResources.Where(x => (x.FirstName == apiModel.FirstName && x.LastName == apiModel.LastName) || (x.Email == apiModel.EmailAddress && apiModel.EmailAddress != null)
|| (x.EmployeeID == apiModel.EmployeeID && apiModel.EmployeeID != null)).FirstOrDefault();
if (!CheckResource(prDbObj, apiModel))
{
ImportDataController.LogImportMessage(processid, "Record has existing allocations and a pending Expenditure Category update and will be skipped ("+apiModel.EmailAddress+")", apiModel.LineNumber, TransactionID);
prSkipped++;
continue;
}
CreditDepartment cdDbObj = DBContext.CreditDepartments.Where(x => x.CreditNumber == apiModel.CreditNumber).FirstOrDefault();
#region Add new CreditDepartment
if (cdDbObj == null)
{
cdDbObj = new CreditDepartment()
{
Id = Guid.NewGuid(),
Name = apiModel.CreditNumber,
CreditNumber = apiModel.CreditNumber
};
ImportDataController.LogImportMessage(processid, "Adding new CreditDepartment for " + apiModel.CreditNumber, apiModel.LineNumber, TransactionID);
DBContext.CreditDepartments.Add(cdDbObj);
DBContext.Entry(cdDbObj).State = EntityState.Added;
DBContext.SaveChanges();
crdtDepartmentAdded++;
}
#endregion
SystemSetting uomSetting = DBContext.SystemSettings.Where(x => x.Type == (int) SystemSettingType.DefaultUOMType).FirstOrDefault();
SystemSetting glSetting = DBContext.SystemSettings.Where(x => x.Type == (int) SystemSettingType.DefaultGLType).FirstOrDefault();
Guid uomId = Guid.Parse(uomSetting.Value);
UOM uomDbObj = DBContext.UOMs.Where(x => x.Id == uomId).FirstOrDefault();
Guid glid = Guid.Parse(glSetting.Value);
GLAccount glDbObj = DBContext.GLAccounts.Where(x => x.Id == glid).FirstOrDefault();
Expenditure exDbObj = DBContext.Expenditures.Where(x => x.jobcode == apiModel.JobCode || x.Name == apiModel.Title).FirstOrDefault();
if (apiModel.JobCode == null || string.IsNullOrEmpty(apiModel.JobCode.Trim()) || apiModel.JobCode.ToLower() == "null")
{
exDbObj = DBContext.Expenditures.Where(x => x.Name == apiModel.Title).FirstOrDefault();
apiModel.JobCode = null;
}
#region Add new Expenditure
if (exDbObj == null)
{
exDbObj = new Expenditure()
{
Id = Guid.NewGuid(),
Name = apiModel.Title,
jobcode = apiModel.JobCode
};
ImportDataController.LogImportMessage(processid, "Adding new Expenditure for " + apiModel.Title, apiModel.LineNumber, TransactionID);
DBContext.Expenditures.Add(exDbObj);
DBContext.Entry(exDbObj).State = EntityState.Added;
DBContext.SaveChanges();
exAdded++;
}
else if (apiModel.JobCode == null)
{
bool updatedEX = false;
if (exDbObj.jobcode != apiModel.JobCode)
{
exDbObj.jobcode = apiModel.JobCode;
updatedEX = true;
}
else if (exDbObj.Name != apiModel.Title)
{
exDbObj.Name = apiModel.Title;
updatedEX = true;
}
if (updatedEX)
{
DBContext.Expenditures.Add(exDbObj);
DBContext.Entry(exDbObj).State = EntityState.Modified;
DBContext.SaveChanges();
}
}
#endregion
ExpenditureCategory excDbObj = null;
#region Use existing ExpenditureCat or add new one
//if (prDbObj == null)
//{
// excDbObj = _dbContext.ExpenditureCategory.Where(x => x.ExpenditureId == exDbObj.Id && x.GLId == glDbObj.Id
// && x.UOMId == uomDbObj.Id && x.CreditId == cdDbObj.Id).FirstOrDefault();
//}
//else
//{
// excDbObj = _dbContext.ExpenditureCategory.Where(x => x.ExpenditureId == exDbObj.Id && x.GLId == glDbObj.Id
// && x.UOMId == uomDbObj.Id && x.CreditId == cdDbObj.Id).FirstOrDefault();
//}
excDbObj = DBContext.ExpenditureCategory.Where(x => x.ExpenditureId == exDbObj.Id).FirstOrDefault();
if (excDbObj == null)
{
excDbObj = new ExpenditureCategory()
{
Id = Guid.NewGuid(),
ExpenditureId = exDbObj.Id,
GLId = glDbObj.Id,
UOMId = uomDbObj.Id,
CreditId = cdDbObj.Id,
Type = (int) ExpenditureCategoryModel.CategoryTypes.Labor,
UseType = (int) ExpenditureCategoryModel.UseTypes.Quantity,
CGEFX = "CG",
Name = apiModel.Title,
AllowResourceAssignment = true
};
ImportDataController.LogImportMessage(processid, "Adding new ExpenditureCategory for Expenditure:" + exDbObj.Name + ", credit department:" + cdDbObj.Name
+ ", unit of measure:" + uomDbObj.Name + ", GL:" + glDbObj.Name, apiModel.LineNumber, TransactionID);
DBContext.ExpenditureCategory.Add(excDbObj);
DBContext.Entry(excDbObj).State = EntityState.Added;
DBContext.SaveChanges();
excAdded++;
}
#endregion
#region Add new PeopleResource
var maxdate = Constants.FISCAL_CALENDAR_MAX_DATE;
if (prDbObj == null)
{
if (!apiModel.StartDate.HasValue)
apiModel.StartDate = DateTime.Now;
if (!apiModel.EndDate.HasValue)
apiModel.EndDate = maxdate;
var ww = (new WorkWeekManager(DBContext)).LoadDefault();
prDbObj = new PeopleResource()
{
Id = Guid.NewGuid(),
FirstName = apiModel.FirstName,
LastName = apiModel.LastName,
IsActiveEmployee = apiModel.IsActiveEmployee,
ExpenditureCategoryId = excDbObj.Id,
StartDate = apiModel.StartDate.Value,
EndDate = apiModel.EndDate.Value,
EmployeeID = apiModel.EmployeeID,
Email = apiModel.EmailAddress,
WorkWeekId = ww.Id
};
ImportDataController.LogImportMessage(processid, "Adding new People Resource:" + apiModel.EmailAddress + ", Expenditure Category:" + excDbObj.Name, apiModel.LineNumber, TransactionID);
DBContext.PeopleResources.Add(prDbObj);
DBContext.Entry(prDbObj).State = EntityState.Added;
DBContext.SaveChanges();
prAdded++;
}
#endregion
#region Update Existing PeopleResource
else //we have a people resouce record now we need to do the update. First load the model from the manager, then call the PeopleResouceController.Edit
{
if (!apiModel.EndDate.HasValue)
apiModel.EndDate = maxdate;
if (!apiModel.StartDate.HasValue)
apiModel.StartDate = prDbObj.StartDate;
ContentLocker.AddLock("PeopleResource", prDbObj.Id.ToString(), userName, DateTime.Now.ToString());
//check to make sure we have any updates that would cause reallication.. if not just do a simple update that
//does not require any calcs
if (prDbObj.ExpenditureCategoryId != excDbObj.Id && prDbObj.EndDate != apiModel.EndDate.Value
&& prDbObj.StartDate != apiModel.StartDate.Value)
{
PeopleResourcesManager Manager = new PeopleResourcesManager(DBContext);
PeopleResourceModel model = Manager.LoadPeopleResourceAsIs(prDbObj.Id, DateTime.UtcNow.Date);
model.PermanentResource = (model.EndDate >= maxdate);
bool doupdate = false;
if (apiModel.EndDate == null)
apiModel.EndDate = model.EndDate;
if (apiModel.StartDate == null)
apiModel.StartDate = model.StartDate;
if (model.EndDate != apiModel.EndDate)
{
model.PermanentResource = (apiModel.EndDate.HasValue && apiModel.EndDate.Value < maxdate);
if (apiModel.EndDate <= DateTime.Now)
{
model.IsActiveEmployee = false;
model.ChangeCapacity = true;
doupdate = true;
}
}
if (model.FirstName != apiModel.FirstName ||
model.LastName != apiModel.LastName ||
model.EmailAddress != apiModel.EmailAddress ||
model.EmployeeID != apiModel.EmployeeID ||
model.EndDate != apiModel.EndDate.Value ||
model.IsActiveEmployee != apiModel.IsActiveEmployee)
doupdate = true;
if (doupdate)
{
model.FirstName = apiModel.FirstName;
model.LastName = apiModel.LastName;
model.EmailAddress = apiModel.EmailAddress;
model.EmployeeID = apiModel.EmployeeID;
model.EndDate = apiModel.EndDate.Value;
model.IsActiveEmployee = apiModel.IsActiveEmployee;
model.ExpenditureCategoryId = excDbObj.Id;
model.TrimStringProperties();
Manager.Save(model);
DBContext.SaveChanges();
prUpdatedCalc++;
ImportDataController.LogImportMessage(processid, "Updated People Resource Record(re calc):" + apiModel.EmailAddress + ", Expenditure Category:" + excDbObj.Name, apiModel.LineNumber, TransactionID);
}
}
else
{
if (prDbObj.FirstName != apiModel.FirstName || prDbObj.LastName != apiModel.LastName || prDbObj.Email != apiModel.EmailAddress ||
prDbObj.EmployeeID != apiModel.EmployeeID)
{
prDbObj.FirstName = apiModel.FirstName;
prDbObj.LastName = apiModel.LastName;
prDbObj.Email = apiModel.EmailAddress;
prDbObj.EmployeeID = apiModel.EmployeeID;
prDbObj.IsActiveEmployee = apiModel.IsActiveEmployee;
DBContext.PeopleResources.Add(prDbObj);
DBContext.Entry(prDbObj).State = EntityState.Modified;
DBContext.SaveChanges();
prUpdatedNoCalc++;
ImportDataController.LogImportMessage(processid, "Updated People Resource Record(no calc):" + apiModel.EmailAddress, apiModel.LineNumber, TransactionID);
}
}
ContentLocker.RemoveLock("PeopleResource", prDbObj.Id.ToString(), userName);
}
#endregion
}
catch (BLLException blEx)
{
ImportDataController.LogImportException(processid, blEx, apiModel.LineNumber, TransactionID);
return false;
}
catch (Exception exception)
{
ImportDataController.LogImportException(processid, exception, apiModel.LineNumber, TransactionID);
return false;
}
}
message = "People Resource import/update finished. ";
message += Environment.NewLine + "Number of Credit Department adds:" + crdtDepartmentAdded.ToString();
message += Environment.NewLine + "Number of Expenditure adds:" + exAdded.ToString();
message += Environment.NewLine + "Number of Expenditure Category adds:" + excAdded.ToString();
message += Environment.NewLine + "Number of People Resource adds:" + prAdded.ToString();
message += Environment.NewLine + "Number of People Resource skipps:" + prSkipped.ToString();
message += Environment.NewLine + "Number of People Resource Updates(re-calc):" + prUpdatedCalc.ToString();
message += Environment.NewLine + "Number of People Resource Updates(non calc):" + prUpdatedNoCalc.ToString();
ImportDataController.LogTrailerMessage(processid, message, TransactionID);
this.TaskStarted("People Resource import/update finished.");
return true;
}
private bool CheckResource(PeopleResource p, PeopleResourceAPIModel a)
{
if (p == null)
return true;
if (p.ExpenditureCategory == null)
return true;
if (p.ExpenditureCategory.Name == a.Title)
return true;
if (p.ExpenditureCategory.Name.ToLower().Trim() == a.Title.Trim().ToLower())
return true;
if (p.PeopleResourceAllocations.Count() > 0)
return false;
return true;
}
//private void AddSystemLogin(PeopleResourceAPIModel aspnetuser)
//{
// try
// {
// string username = aspnetuser.EmailAddress.Substring(0, aspnetuser.EmailAddress.IndexOf("@"));
// var user = this.DBContext.AspNetUsers.Where(x => x.Email == aspnetuser.EmailAddress).FirstOrDefault();
// if (user == null)
// {
// Guid UserID = Guid.NewGuid();
// this.DBContext.AspNetUsers.Add(new AspNetUser()
// {
// Id = UserID.ToString(),
// UserName = username,
// Discriminator = "ApplicationUser",
// FirstName = aspnetuser.FirstName,
// LastName = aspnetuser.LastName,
// Email = aspnetuser.EmailAddress,
// PreferredTotalsDisplaying = false,
// Type = (int) UserType.Active,
// PreferredResourceAllocation = true,
// OverUnderCoefficient = 01.00m
// });
// }
// //accountManagerEntity.SaveChanges();
// }
// catch (Exception createNewUseEx)
// {
// }
//}
public void BulkPeopleResourceRecordEditAsync(List<PeopleResourceAPIModel> apiModels, Guid savedId)
{
BackgroundProcess.RunJob(BulkPeopleResourceRecordEdit, apiModels, savedId);
}
#endregion
#region Rate Updates
public bool RateScenarioUpdates(RateModel model, Guid savedId, CancellationToken ct)
{
#if DEBUG
var watch1 = new System.Diagnostics.Stopwatch();
watch1.Start();
Logger.Debug("Start EditRate RateScenarioUpdates");
#endif
var dbContext = new EnVisageEntities();
var userName = dbContext.AspNetUsers.FirstOrDefault(x => x.Id == UserID.ToString())?.UserName;
cancellationToken = ct;
HostingEnvironment.RegisterObject(this);
var m = new ExpenditureCategoryManager(null);
var ec = m.Load(model.ExpenditureCategoryId);
var message = "A rate update has been submited for the " + ec.Name + " expenditure category";
if (model.Id == Guid.Empty)
message = "A new rate has been submited for the " + ec.Name + " expenditure category";
var nTimes = 0;
while (!ContentLocker.AddLock("Rate", savedId.ToString(), userName, DateTime.Now.ToString()).Status)
{
nTimes++;
if (nTimes > 5)
{
message = "Unable to obtain a lock for " + ec.Name + " expenditure category rate update. Please try again later. Thanks";
TaskHadError(message);
return false;
}
try
{
Thread.Sleep(TimeSpan.FromSeconds(1));
}
catch
{
// ignored
}
}
TaskStarted(message);
#if DEBUG
watch1.Stop();
System.Diagnostics.Debug.WriteLine($"EditRate RateScenarioUpdates pre Recalculate has taken {watch1.ElapsedMilliseconds} ms");
Logger.Debug($"EditRate RateScenarioUpdates pre Recalculate {watch1.ElapsedMilliseconds} ms");
watch1 = new System.Diagnostics.Stopwatch();
watch1.Start();
#endif
var scenarioManager = new ScenarioManager(dbContext);
scenarioManager.ApplyRateAndRecalculateScenarios(model);
#if DEBUG
watch1.Stop();
System.Diagnostics.Debug.WriteLine($"EditRate RateScenarioUpdates ApplyRateAndRecalculateScenarios has taken {watch1.ElapsedMilliseconds} ms");
Logger.Debug($"EditRate RateScenarioUpdates ApplyRateAndRecalculateScenarios {watch1.ElapsedMilliseconds} ms");
watch1 = new System.Diagnostics.Stopwatch();
watch1.Start();
#endif
try
{
if (model.Type == RateModel.RateType.Global)
scenarioManager.RecalculateCapacityScenariosRates(model);
#if DEBUG
watch1.Stop();
System.Diagnostics.Debug.WriteLine($"EditRate RateScenarioUpdates RecalculateCapacityScenariosRates has taken {watch1.ElapsedMilliseconds} ms");
Logger.Debug($"EditRate RateScenarioUpdates RecalculateCapacityScenariosRates {watch1.ElapsedMilliseconds} ms");
watch1 = new System.Diagnostics.Stopwatch();
watch1.Start();
#endif
if (!cancellationToken.IsCancellationRequested)
{
dbContext.BulkSaveChanges();
}
#if DEBUG
watch1.Stop();
System.Diagnostics.Debug.WriteLine($"EditRate RateScenarioUpdates SaveChanges has taken {watch1.ElapsedMilliseconds} ms");
Logger.Debug($"EditRate RateScenarioUpdates SaveChanges {watch1.ElapsedMilliseconds} ms");
watch1 = new System.Diagnostics.Stopwatch();
watch1.Start();
#endif
message = "The rate update for the " + ec.Name + " expenditure category has completed";
if (model.Id == Guid.Empty)
message = "The new rate the " + ec.Name + " expenditure category has been added";
TaskFinished(message);
ContentLocker.RemoveLock("Rate", savedId.ToString(), userName);
#if DEBUG
watch1.Stop();
System.Diagnostics.Debug.WriteLine($"EditRate RateScenarioUpdates end save has taken {watch1.ElapsedMilliseconds} ms");
Logger.Debug($"EditRate RateScenarioUpdates end save All {watch1.ElapsedMilliseconds} ms");
#endif
return true;
}
catch (Exception dds)
{
var logger = NLog.LogManager.GetCurrentClassLogger();
logger.Error(dds);
message = "The rate update for the " + ec.Name + " expenditure category has failed please contact your system administrator.";
TaskHadError(message);
return false;
}
}
public void RateScenarioUpdatesAsync(RateModel model, Guid savedId)
{
BackgroundProcess.RunJob(RateScenarioUpdates, model, savedId);
}
#endregion
#region CRM Updates
public void RemoveResourceCRMAsync(Guid ProjectId, string resourceEmail, AccessInf crmDal)
{
BackgroundProcess.RunJob(RemoveResourceCRM,ProjectId, resourceEmail, crmDal);
}
public void AddResourceCRMAsync(Guid ProjectId, string resourceEmail, AccessInf crmDal)
{
BackgroundProcess.RunJob(AddResourceCRM, ProjectId, resourceEmail, crmDal);
}
public bool RemoveResourceCRM(Guid ProjectId,string resouceEmail, AccessInf crmDal, CancellationToken ct)
{
if (crmDal == null)
return false;
IntegrationManager intMan = new IntegrationManager(new EnVisageEntities());
Dictionary<string, string> attbData = new Dictionary<string, string>();
var mapping = intMan.getFieldModelsForTable("RemoveResource", "Remove").FirstOrDefault();
if (mapping == null)
return false;
crmDal.RemoveResouceFromProject(mapping.EntityName, ProjectId, resouceEmail);
return true;
}
public bool AddResourceCRM(Guid ProjectId, string resouceEmail, AccessInf crmDal, CancellationToken ct)
{
if (crmDal == null)
return false;
IntegrationManager intMan = new IntegrationManager(new EnVisageEntities());
Dictionary<string, string> attbData = new Dictionary<string, string>();
var mappings = intMan.getFieldModelsForTable("AddResource", "Add");
if (mappings == null)
mappings = new List<Integration2Prevu>();
string crmEntity = "";
if (mappings.Count > 0)
{
foreach(Integration2Prevu map in mappings)
{
map.TrimStringProperties();
if (map.PrevuName == "Email")
{
crmEntity = map.EntityName;
attbData.Add(map.FieldName, resouceEmail);
}else if (map.DefaultValue != null)
{
crmEntity = map.EntityName;
attbData.Add(map.FieldName, map.DefaultValue.Trim());
}
}
}
if (attbData.Count > 0)
crmDal.addResourceToProject(crmEntity, attbData, ProjectId);
return true;
}
public void UpdateCRMAsync(Dictionary<string, Dictionary<string, string>> data,Guid parentKey, AccessInf crmDal,string action)
{
BackgroundProcess.RunJob(UpdateCRM, data,parentKey,crmDal, action);
}
public bool UpdateCRM(Dictionary<string,Dictionary<string,string>> data,Guid parentKey, AccessInf crmDal, string action,CancellationToken ct)
{
if (crmDal == null)
return false;
IntegrationManager intMan = new IntegrationManager(new EnVisageEntities());
Dictionary<string, Dictionary<string, object>> crmPassThruData = new Dictionary<string, Dictionary<string, object>>();
foreach (string table in data.Keys)
{
var mappings = intMan.getFieldModelsForTable(table,action);
if (mappings == null)
mappings = new List<Integration2Prevu>();
if (mappings.Count > 0)
{
Dictionary<string, object> attbData = new Dictionary<string, object>();
Dictionary<string, string> cols = data[table];
foreach(string column in cols.Keys)
{
var mapping = mappings.Where(x => x.PrevuName == column).FirstOrDefault();
if (mapping != null)
{
string val = cols[column];
System.Type t = System.Type.GetType(mapping.FieldType.Trim());
object valObj = Convert.ChangeType(val, t);
if (crmPassThruData.ContainsKey(mapping.EntityName))
attbData = crmPassThruData[mapping.EntityName];
attbData.Add(mapping.FieldName, valObj);
crmPassThruData[mapping.EntityName] = attbData;
}
}
}
}
if (crmPassThruData.Count > 0)
crmDal.Update(crmPassThruData, parentKey);
return true;
}
#endregion
#region notification methods
private void TaskStarted(string message)
{
if (NotificationContext == null)
NotificationContext = new EnVisageEntities();
NotificationManager nm = new NotificationManager(this.NotificationContext);
NotificationModel m = new NotificationModel();
if (TaskID == Guid.Empty)
TaskID = Guid.NewGuid();
m.title = "Task Started";
m.description = message;
m.NotificationGroup = NotificationGroupType.User;
m.ParentId = this.UserID;
m.Id = TaskID;
m.NotificationViewed = false;
m.NotificationDate = DateTime.Now;
m.type = NotificationType.Task;
nm.Save(m);
NotificationContext.SaveChanges();
}
private void TaskHadError(string message)
{
if (NotificationContext == null)
NotificationContext = new EnVisageEntities();
NotificationManager nm = new NotificationManager(NotificationContext);
Notification no = nm.Load(this.TaskID);
NotificationModel m = new NotificationModel(no,NotificationContext);
m.title = "Task Had Errors";
m.type = NotificationType.Error;
m.description = message;
nm.Save(m);
NotificationContext.SaveChanges();
}
private void TaskFinished(string message)
{
if (NotificationContext == null)
NotificationContext = new EnVisageEntities();
NotificationManager nm = new NotificationManager(NotificationContext);
Notification no=nm.Load(this.TaskID);
NotificationModel m = new NotificationModel(no, NotificationContext);
m.title = "Task Finished";
m.description = message;
nm.Save(m);
NotificationContext.SaveChanges();
}
#endregion
}
}