public void Update(EntityHistory visitas, string FechaCompra, string TipoServicio, string SintomaFalla) { DateTime compra = DateTime.Parse(FechaCompra); var objRepository = new RepositoryHistory(); EntityHistory data = new EntityHistory() { PK_HistoryID = visitas.PK_HistoryID, FK_InstalledBaseID = visitas.FK_InstalledBaseID, FK_ClientID = visitas.FK_ClientID, FK_OrderID = visitas.FK_OrderID, OrderID = visitas.OrderID, OrderStatus = visitas.OrderStatus, ItemStatus = visitas.ItemStatus, Guaranty = TipoServicio, ShopDate = compra, CloseDate = visitas.CloseDate, FailureID1 = visitas.FailureID1, Failure1 = SintomaFalla, FailureID2 = visitas.FailureID2, Failure2 = visitas.Failure2, FailureID3 = visitas.FailureID3, Failure3 = visitas.Failure3, Status = visitas.Status, CreateDate = visitas.CreateDate, ModifyDate = DateTime.UtcNow }; data = objRepository.Update(data); }
private bool shouldDisplay(EntityHistory eh) { RecentlyVisitedTypeList list = PageWorkItem.RootWorkItem.State[EntityBreadCrumb.CONST_RECENTTYPESLIST] as RecentlyVisitedTypeList ?? new RecentlyVisitedTypeList(); return list.VisitedTypes.Contains(eh.EntityType); }
public static HistoryResource ToResource(this EntityHistory model) { if (model == null) { return(null); } return(new HistoryResource { Id = model.Id, BookId = model.BookId, AuthorId = model.AuthorId, SourceTitle = model.SourceTitle, Quality = model.Quality, //QualityCutoffNotMet Date = model.Date, DownloadId = model.DownloadId, EventType = model.EventType, Data = model.Data //Episode //Series }); }
public EntityHistory[] RemoveDoublePurge(EntityHistory[] entitiesPlan) { var newPlan = new List <EntityHistory>(); foreach (var e in entitiesPlan) { var newE = new EntityHistory(); newE.Id = e.Id; newE.Name = e.Name; newE.Parent = e.Parent; newE.Periods = new List <LotInfoPeriodGantt>(); var tempPeriods = e.Periods.OrderBy(x => x.start).ToList(); double tempStart = 0; double tempEnd = 0; double tempDuration = 0; for (var p = 0; p < tempPeriods.Count; p++) { if ((p < tempPeriods.Count - 1 && tempPeriods[p].lot.StartsWith("After") && tempPeriods[p + 1].lot.StartsWith("Before"))) { tempStart = tempPeriods[p].start; tempEnd = tempPeriods[p].end; tempDuration = tempDuration + tempEnd - tempStart; continue; } tempPeriods[p].start = tempPeriods[p].start - tempDuration; tempPeriods[p].end = tempPeriods[p].end - tempDuration; newE.Periods.Add(tempPeriods[p]); } newPlan.Add(newE); } return(newPlan.ToArray()); }
public void Insert(int FK_InstalledBaseID, int FK_ClientID, int FK_OrderID, string OrderID, string FechaCompra, string TipoServicio, string SintomaFalla) { DateTime compra = DateTime.Parse(FechaCompra); var objRepository = new RepositoryHistory(); EntityHistory data = new EntityHistory() { PK_HistoryID = 0, FK_InstalledBaseID = FK_InstalledBaseID, FK_ClientID = FK_ClientID, FK_OrderID = FK_OrderID, OrderID = OrderID, OrderStatus = "", ItemStatus = "", Guaranty = TipoServicio, ShopDate = compra, CloseDate = DateTime.UtcNow, FailureID1 = "", Failure1 = SintomaFalla, FailureID2 = "", Failure2 = "", FailureID3 = "", Failure3 = "", Status = true, CreateDate = DateTime.Now, ModifyDate = DateTime.UtcNow }; data = objRepository.Insert(data); }
private bool shouldDisplay(EntityHistory eh) { RecentlyVisitedTypeList list = PageWorkItem.RootWorkItem.State[EntityBreadCrumb.CONST_RECENTTYPESLIST] as RecentlyVisitedTypeList ?? new RecentlyVisitedTypeList(); return(list.VisitedTypes.Contains(eh.EntityType)); }
public async Task Handle(ProductCratedIntegrationEvent notification, CancellationToken cancellationToken) { var history = EntityHistory.Create(notification.Id, notification.Name, EventType.Create, notification.CreatedBy, notification.CreatedOn); await _repository.Add(history); await _repository.CommitAsync(); }
/// <summary> /// 获取实体历史 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="entity">实体对象</param> /// <returns>实体历史</returns> public IEntityHistory GetEntityHistory <T>(T entity) where T : PlainEntity { DbEntityEntry <T> entry = this._dbContext.ChangeTracker.Entries <T>().FirstOrDefault(x => x.Entity.Id == entity.Id); #region # 验证 if (entry == null) { return(null); } #endregion LoginInfo loginInfo = GetLoginInfo?.Invoke(); ActionType actualActionType; IDictionary <string, object> beforeSnapshot = new Dictionary <string, object>(); IDictionary <string, object> afterSnapshot = new Dictionary <string, object>(); if (entry.State == EntityState.Added) { actualActionType = ActionType.Create; foreach (string propertyName in entry.CurrentValues.PropertyNames) { DbPropertyEntry propertyEntry = entry.Property(propertyName); afterSnapshot[propertyName] = propertyEntry.CurrentValue; } } else if (entry.State == EntityState.Modified) { actualActionType = ActionType.Update; foreach (string propertyName in entry.OriginalValues.PropertyNames) { DbPropertyEntry propertyEntry = entry.Property(propertyName); if (propertyEntry.OriginalValue?.ToString() != propertyEntry.CurrentValue?.ToString()) { beforeSnapshot[propertyName] = propertyEntry.OriginalValue; afterSnapshot[propertyName] = propertyEntry.CurrentValue; } } } else if (entry.State == EntityState.Deleted) { actualActionType = ActionType.Delete; foreach (string propertyName in entry.OriginalValues.PropertyNames) { DbPropertyEntry propertyEntry = entry.Property(propertyName); beforeSnapshot[propertyName] = propertyEntry.OriginalValue; } } else { return(null); } EntityHistory entityHistory = new EntityHistory(actualActionType, typeof(T), entry.Entity.Id, beforeSnapshot, afterSnapshot, loginInfo?.LoginId, loginInfo?.RealName); return(entityHistory); }
/// <summary> /// 获取实体历史列表 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="actionType">动作类型</param> /// <returns>实体历史列表</returns> public ICollection <IEntityHistory> GetEntityHistories <T>(ActionType?actionType = null) where T : PlainEntity { LoginInfo loginInfo = GetLoginInfo?.Invoke(); ICollection <IEntityHistory> entityHistories = new HashSet <IEntityHistory>(); IEnumerable <DbEntityEntry <T> > entries = from entry in this._dbContext.ChangeTracker.Entries <T>() where actionType == null || entry.State == (EntityState)actionType.Value select entry; foreach (DbEntityEntry <T> entry in entries) { ActionType actualActionType; IDictionary <string, object> beforeSnapshot = new Dictionary <string, object>(); IDictionary <string, object> afterSnapshot = new Dictionary <string, object>(); if (entry.State == EntityState.Added) { actualActionType = ActionType.Create; foreach (string propertyName in entry.CurrentValues.PropertyNames) { DbPropertyEntry propertyEntry = entry.Property(propertyName); afterSnapshot[propertyName] = propertyEntry.CurrentValue; } } else if (entry.State == EntityState.Modified) { actualActionType = ActionType.Update; foreach (string propertyName in entry.OriginalValues.PropertyNames) { DbPropertyEntry propertyEntry = entry.Property(propertyName); if (propertyEntry.OriginalValue?.ToString() != propertyEntry.CurrentValue?.ToString()) { beforeSnapshot[propertyName] = propertyEntry.OriginalValue; afterSnapshot[propertyName] = propertyEntry.CurrentValue; } } } else if (entry.State == EntityState.Deleted) { actualActionType = ActionType.Delete; foreach (string propertyName in entry.OriginalValues.PropertyNames) { DbPropertyEntry propertyEntry = entry.Property(propertyName); beforeSnapshot[propertyName] = propertyEntry.OriginalValue; } } else { continue; } EntityHistory entityHistory = new EntityHistory(actualActionType, typeof(T), entry.Entity.Id, beforeSnapshot, afterSnapshot, loginInfo?.LoginId, loginInfo?.RealName); entityHistories.Add(entityHistory); } return(entityHistories); }
public EntityHistory getHistory() { EntityHistory history = new EntityHistory(); history.createdBy = 0L; history.createdDate = new DateTime(); history.updatedBy = 0L; history.updatedDate = new DateTime(); return(history); }
private void ResolveTaskHistory(EntityHistory taskHistory) { Author = taskHistory.Author; CreationDate = taskHistory.CreationDate.ToString("g"); CommitChanges.Clear(); foreach (var commitChange in taskHistory.Changes) { CommitChanges.Add(new CommitChangesViewModel(commitChange, _taskStateQueryService)); } }
async Task <TEntity> EntityUpdating(TEntity entity) { // Get previous history points var previousHistories = await _entityHistoryStore.QueryAsync() .Take(1) .Select <EntityHistoryQueryParams>(q => { q.EntityId.Equals(entity.Id); q.EntityReplyId.Equals(0); }) .OrderBy("CreatedDate", OrderBy.Desc) .ToList(); // Get the most recently added history point EntityHistory previousHistory = null; if (previousHistories?.Data != null) { previousHistory = previousHistories.Data[0]; } // If we have previous history we don't need to add a starting point if (previousHistory != null) { return(entity); } // Get existing entity before any changes var existingEntity = await _entityStore.GetByIdAsync(entity.Id); // We need an existing entity if (existingEntity == null) { return(entity); } // If we don't have any existing history points add our // existing entity (before updates) as the starting / original history point await _entityHistoryManager.CreateAsync(new EntityHistory() { EntityId = existingEntity.Id, Message = existingEntity.Message, Html = existingEntity.Html, CreatedUserId = existingEntity.EditedUserId > 0 ? existingEntity.EditedUserId : existingEntity.CreatedUserId, CreatedDate = existingEntity.EditedDate ?? existingEntity.CreatedDate }); return(entity); }
private bool ValuesSet(EntityHistory hist) { switch (hist.EntityType.Name) { case "IAccount": IAccount account = EntityFactory.GetById <IAccount>(hist.EntityId.ToString()); Account.LookupResultValue = account; Contact.LookupResultValue = GetPrimaryContact(account.Contacts); return(true); case "IContact": IContact contact = EntityFactory.GetById <IContact>(hist.EntityId.ToString()); Contact.LookupResultValue = contact; Account.LookupResultValue = contact.Account; return(true); case "IOpportunity": IOpportunity opportunity = EntityFactory.GetById <IOpportunity>(hist.EntityId.ToString()); Opportunity.LookupResultValue = opportunity; Account.LookupResultValue = opportunity.Account; foreach (IOpportunityContact oppContact in opportunity.Contacts) { if (oppContact.IsPrimary.HasValue) { if ((bool)oppContact.IsPrimary) { Contact.LookupResultValue = oppContact.Contact; break; } } } return(true); case "ITicket": ITicket ticket = EntityFactory.GetById <ITicket>(hist.EntityId.ToString()); Ticket.LookupResultValue = ticket; Account.LookupResultValue = ticket.Account; Contact.LookupResultValue = ticket.Contact; return(true); case "ILead": SetDivVisible(VisibleDiv.Lead); ILead lead = EntityFactory.GetById <ILead>(hist.EntityId.ToString()); LeadId.LookupResultValue = lead; Company.Text = lead.Company; return(true); } return(false); }
public static async Task AggregateEntityHistory( this IRepository _repository, string entityId, string userId, OperationType operationType, bool saveChanges = true) { var entityHistory = new EntityHistory(entityId, userId, operationType); _repository.Add(entityHistory); if (saveChanges) { await _repository.SaveChangesAsync(); } }
/// <summary> /// 从Redis内存移除,并保存到数据库 /// </summary> /// <param name="keys"></param> public static void RemoveToDatabase(params string[] keys) { var entityKeys = new List <string>(); var entityList = new List <EntityHistory>(); RedisConnectionPool.ProcessReadOnly(client => { foreach (var k in keys) { try { string key = k; string setId = key + "_remove"; if (key.EndsWith("_remove")) { setId = key; key = key.Replace("_remove", ""); } else { if (client.ContainsKey(key)) { client.Rename(key, setId); } } entityKeys.Add(setId); //转存到DB使用protobuf byte[] keyValues = ProtoBufUtils.Serialize(client.HGetAll(setId)); var history = new EntityHistory() { Key = key, Value = keyValues }; entityList.Add(history); } catch (Exception ex) { TraceLog.WriteError("Redis cache remove key:{0} to Database error:{1}", k, ex); } } }); if (entityList.Count > 0) { DataSyncManager.GetDataSender().Send <EntityHistory>(entityList.ToArray()); RedisConnectionPool.ProcessReadOnly(client => client.RemoveAll(entityKeys)); } }
async Task <TEntity> EntityUpdated(TEntity entity) { // Get previous history points var previousHistories = await _entityHistoryStore.QueryAsync() .Take(1) .Select <EntityHistoryQueryParams>(q => { q.EntityId.Equals(entity.Id); q.EntityReplyId.Equals(0); }) .OrderBy("CreatedDate", OrderBy.Desc) .ToList(); // Get the most recently added history point EntityHistory previousHistory = null; if (previousHistories?.Data != null) { previousHistory = previousHistories.Data[0]; } // Ensure we actually have changes if (previousHistory != null) { // Don't save a history point if the Html has not changed if (entity.Html == previousHistory.Html) { return(entity); } } // Create entity history point await _entityHistoryManager.CreateAsync(new EntityHistory() { EntityId = entity.Id, Message = entity.Message, Html = entity.Html, CreatedUserId = entity.EditedUserId > 0 ? entity.EditedUserId : entity.ModifiedUserId, CreatedDate = entity.EditedDate ?? DateTimeOffset.UtcNow }); return(entity); }
public virtual void AfterSave(bool isUpdate) { #region if critical entity, log it if (this is ICriticalEntity) { if (isUpdate) { //Provider.Database.ClearEntityWebCache(this.GetType(), this.Id); IDatabaseEntityMinimal originalEntity = Provider.Database.Read(this.GetType(), "Id={0}", this.Id); string changes = originalEntity.CompareFields(this); if (!string.IsNullOrWhiteSpace(changes)) { EntityHistory eh = new EntityHistory() { EntityId = this.Id, EntityName = this.GetType().Name, MemberId = Provider.CurrentMember.Id, Operation = EntityOperation.Update }; eh.Save(); EntityHistoryData ehd = new EntityHistoryData() { Changes = changes, EntityHistoryId = eh.Id }; ehd.Save(); } } else { EntityHistory eh = new EntityHistory() { EntityId = this.Id, EntityName = this.GetType().Name, MemberId = Provider.CurrentMember.Id, Operation = EntityOperation.Insert }; eh.Save(); } } #endregion }
private void RemoveFromEntityHistory() { if (EntityContext.EntityHistory.Count <= 0) { return; } EntityHistory historyRecord = EntityContext.EntityHistory[0]; if (historyRecord == null) { return; } if (historyRecord.EntityId.ToString() == Activity.ActivityId) { EntityContext.EntityHistory.Remove(historyRecord); } }
protected HistoryResource MapToResource(EntityHistory model, bool includeAuthor, bool includeBook) { var resource = model.ToResource(); if (includeAuthor) { resource.Author = model.Author.ToResource(); } if (includeBook) { resource.Book = model.Book.ToResource(); } if (model.Author != null) { resource.QualityCutoffNotMet = _upgradableSpecification.QualityCutoffNotMet(model.Author.QualityProfile.Value, model.Quality); } return(resource); }
private static bool shouldDisplay(EntityHistory eh) { //we need a dynamic way to determine if a an entity has a page so we can link to it if (eh.EntityType == typeof(IContactLeadSource)) { return false; } if (eh.EntityType == typeof(IUserNotification)) { return false; } if (eh.EntityType == typeof(ITargetResponse)) { return false; } if (eh.EntityType == typeof(IAssociation)) { return false; } return (EntityFactory.GetById(eh.EntityType, eh.EntityId) != null); }
/// <summary> /// Loads the default setting for the change password form. /// </summary> /// <param name="form">The change password form.</param> /// <param name="args">The <see cref="System.EventArgs"/> instance containing the event data.</param> public static void OnChangePasswordLoad(IUserChangePassword form, EventArgs args) { IEntityHistoryService entities = ApplicationContext.Current.Services.Get <IEntityHistoryService>(false); if (entities != null) { EntityHistory entity = entities[0]; if (entity != null && entity.EntityType == typeof(IUser)) { if (form.usrUser.LookupResultValue == null) { form.usrUser.LookupResultValue = entity.EntityId; } form.ctrlstButtons.Visible = true; } else { form.ctrlstButtons.Visible = false; } } }
/// <summary> /// 从Redis内存移除,并保存到数据库 /// </summary> /// <param name="keys"></param> public static void RemoveToDatabase(params string[] keys) { RedisManager.Process(client => { foreach (var k in keys) { try { string key = k; string setId = key + "_remove"; if (key.EndsWith("_remove")) { setId = key; key = key.Replace("_remove", ""); } else { if (client.ContainsKey(key)) { client.Rename(key, setId); } } var buffer = client.Get <byte[]>(setId); if (buffer != null) { var history = new EntityHistory() { Key = key, Value = buffer }; DataSyncManager.GetDataSender().Send(history); client.Remove(setId); } } catch (Exception ex) { TraceLog.WriteError("Redis cache remove key:{0} to Database error:{1}", k, ex); } } }); }
/// <summary> /// Loads the default setting for the change password form. /// </summary> /// <param name="form">The change password form.</param> /// <param name="args">The <see cref="System.EventArgs"/> instance containing the event data.</param> public static void OnChangePasswordLoad(IUserChangePassword form, EventArgs args) { IEntityHistoryService entities = ApplicationContext.Current.Services.Get <IEntityHistoryService>(false); if (entities != null) { EntityHistory entity = entities[0]; if (entity != null && entity.EntityType.Equals(typeof(IUser))) { //form.usrUser.Enabled = (entity.EntityId.ToString().Trim().Equals("ADMIN")); if (form.usrUser.LookupResultValue == null) { form.usrUser.LookupResultValue = entity.EntityId; } form.ctrlstButtons.Visible = true; } else { form.ctrlstButtons.Visible = false; //form.usrUser.LookupResultValue = Sage.SalesLogix.API.MySlx.Security.CurrentSalesLogixUser; } } }
internal static EntityHistory EntityHistory(this EntityEntry entry, JsonSerializer jsonSerializer) { var entityHistory = new EntityHistory { EntityName = entry.Metadata.Relational().TableName }; // Get the mapped properties for the entity type. // (include shadow properties, not include navigations & references) var properties = entry.Properties; var json = new JObject(); switch (entry.State) { case EntityState.Added: foreach (var prop in properties) { if (prop.Metadata.IsKey() || prop.Metadata.IsForeignKey()) { continue; } json[prop.Metadata.Name] = prop.CurrentValue != null ? JToken.FromObject(prop.CurrentValue, jsonSerializer) : JValue.CreateNull(); } entityHistory.EntityId = entry.PrimaryKey(); entityHistory.EntityState = EntityState.Added; entityHistory.ChangeHistory = json.ToString(); break; case EntityState.Modified: var before = new JObject(); var after = new JObject(); foreach (var prop in properties) { if (prop.IsModified) { before[prop.Metadata.Name] = prop.OriginalValue != null ? JToken.FromObject(prop.OriginalValue, jsonSerializer) : JValue.CreateNull(); after[prop.Metadata.Name] = prop.CurrentValue != null ? JToken.FromObject(prop.CurrentValue, jsonSerializer) : JValue.CreateNull(); } } json["before"] = before; json["after"] = after; entityHistory.EntityId = entry.PrimaryKey(); entityHistory.EntityState = EntityState.Modified; entityHistory.ChangeHistory = json.ToString(); break; case EntityState.Deleted: foreach (var prop in properties) { json[prop.Metadata.Name] = prop.OriginalValue != null ? JToken.FromObject(prop.OriginalValue, jsonSerializer) : JValue.CreateNull(); } entityHistory.EntityId = entry.PrimaryKey(); entityHistory.EntityState = EntityState.Deleted; entityHistory.ChangeHistory = json.ToString(); break; case EntityState.Detached: case EntityState.Unchanged: default: throw new NotSupportedException("AutoHistory only support Deleted and Modified entity."); } return(entityHistory); }
public bool TryLoadHistory <T>(string redisKey, out List <T> dataList) { bool result = false; dataList = null; SchemaTable schemaTable; if (EntitySchemaSet.TryGet <EntityHistory>(out schemaTable)) { try { var provider = DbConnectionProvider.CreateDbProvider(schemaTable); if (provider == null) { //DB is optional and can no DB configuration dataList = new List <T>(); return(true); } TransReceiveParam receiveParam = new TransReceiveParam(redisKey); receiveParam.Schema = schemaTable; int maxCount = receiveParam.Schema.Capacity; var filter = new DbDataFilter(maxCount); string key = schemaTable.Keys[0]; filter.Condition = provider.FormatFilterParam(key); filter.Parameters.Add(key, redisKey); receiveParam.DbFilter = filter; receiveParam.Capacity = maxCount; List <EntityHistory> historyList; if (_dbTransponder.TryReceiveData(receiveParam, out historyList)) { if (historyList.Count == 0) { dataList = new List <T>(); result = true; } else { EntityHistory history = historyList[0]; RedisManager.Process(client => client.Set(redisKey, history.Value)); var dataSet = ProtoBufUtils.Deserialize <Dictionary <string, T> >(history.Value); if (dataSet != null) { dataList = dataSet.Values.ToList(); result = true; } } } } catch (Exception ex) { TraceLog.WriteError("Try load Redis's history key:{0}\r\nerror:{1}", redisKey, ex); } } else { dataList = new List <T>(); result = true; } return(result); }
public bool TryLoadHistory <T>(string redisKey, out List <T> dataList) { redisKey = RedisConnectionPool.GetRedisEntityKeyName(redisKey); bool result = false; dataList = null; SchemaTable schemaTable; if (EntitySchemaSet.TryGet <EntityHistory>(out schemaTable)) { try { var provider = DbConnectionProvider.CreateDbProvider(schemaTable); if (provider == null) { //DB is optional and can no DB configuration dataList = new List <T>(); return(true); } TransReceiveParam receiveParam = new TransReceiveParam(redisKey); receiveParam.Schema = schemaTable; int maxCount = receiveParam.Schema.Capacity; var filter = new DbDataFilter(maxCount); string key = schemaTable.Keys[0]; filter.Condition = provider.FormatFilterParam(key); filter.Parameters.Add(key, redisKey); receiveParam.DbFilter = filter; receiveParam.Capacity = maxCount; List <EntityHistory> historyList; if (_dbTransponder.TryReceiveData(receiveParam, out historyList)) { EntityHistory history = historyList.Count > 0 ? historyList[0] : null; if (history != null && history.Value != null && history.Value.Length > 0) { byte[][] bufferBytes = ProtoBufUtils.Deserialize <byte[][]>(history.Value); byte[][] keys = bufferBytes.Where((b, index) => index % 2 == 0).ToArray(); byte[][] values = bufferBytes.Where((b, index) => index % 2 == 1).ToArray(); RedisConnectionPool.Process(client => client.HMSet(redisKey, keys, values)); dataList = values.Select(value => ProtoBufUtils.Deserialize <T>(value)).ToList(); result = true; } else { dataList = new List <T>(); result = true; } } } catch (Exception ex) { TraceLog.WriteError("Try load Redis's history key:{0}\r\nerror:{1}", redisKey, ex); } } else { dataList = new List <T>(); result = true; } return(result); }
public void Update(EntityHistory data) { new RepositoryHistory().Update(data); }
static void Main(string[] args) { var arrODS = FacadeOrder.GetAll().Where(p => p.OrderExecuteDate.Equals(new DateTime(2017, 11, 8))); int j = 1; Console.WriteLine("Total: " + arrODS.Count().ToString()); foreach (var i in arrODS) { try { Console.WriteLine(j.ToString() + " de " + arrODS.Count().ToString()); var dataODS = FacadeOrder.Get(i.PK_OrderID); var dataClient = FacadeClient.GetByID(i.FK_ClientID); var dataBaseInstalled = FacadeInstalledBase.GetByID(dataODS.FK_InstalledBaseID); var dataProduct = FacadeProduct.GetByID(dataBaseInstalled.FK_ProductID.Value); var dataHistory = FacadeMabe.HistoryODSByClient(dataClient.ClientID, dataBaseInstalled.InstalledBaseID); // insertar datos order history foreach (var item in dataHistory) { var dataDBHistory = FacadeHistory.GetByOrderID(dataODS.PK_OrderID); if (dataDBHistory.Where(p => p.OrderID == item.ID_Oper).Count() > 0) { // update var entity = dataDBHistory.Where(p => p.OrderID == item.ID_Oper).FirstOrDefault(); entity.CloseDate = ParseDate(item.Fecha_Cierre_Orden); entity.Failure1 = string.IsNullOrEmpty(item.Desc_ID_Falla1) ? "" : item.Desc_ID_Falla1; entity.Failure2 = string.IsNullOrEmpty(item.Desc_ID_Falla2) ? "" : item.Desc_ID_Falla2; entity.Failure3 = string.IsNullOrEmpty(item.Desc_ID_Falla3) ? "" : item.Desc_ID_Falla3; entity.FailureID1 = string.IsNullOrEmpty(item.ID_Falla1) ? "" : item.ID_Falla1; entity.FailureID2 = string.IsNullOrEmpty(item.ID_Falla2) ? "" : item.ID_Falla2; entity.FailureID3 = string.IsNullOrEmpty(item.ID_Falla3) ? "" : item.ID_Falla3; entity.FK_ClientID = dataODS.FK_ClientID; entity.FK_InstalledBaseID = dataODS.FK_InstalledBaseID; entity.FK_OrderID = dataODS.PK_OrderID; entity.Guaranty = string.IsNullOrEmpty(item.Tipo_Serv) ? "" : item.Tipo_Serv; entity.ItemStatus = string.IsNullOrEmpty(item.Estatus_Visita) ? "" : item.Estatus_Visita; entity.ModifyDate = DateTime.UtcNow; entity.OrderID = string.IsNullOrEmpty(item.ID_Oper) ? "" : item.ID_Oper; entity.OrderStatus = string.IsNullOrEmpty(item.Estatus_Oper) ? "" : item.Estatus_Oper; entity.ShopDate = new DateTime(1980, 1, 1); entity.Status = true; FacadeHistory.Update(entity); } else { // insert var entity = new EntityHistory(); entity.CloseDate = ParseDate(item.Fecha_Cierre_Orden); entity.CreateDate = DateTime.UtcNow; entity.Failure1 = string.IsNullOrEmpty(item.Desc_ID_Falla1) ? "" : item.Desc_ID_Falla1; entity.Failure2 = string.IsNullOrEmpty(item.Desc_ID_Falla2) ? "" : item.Desc_ID_Falla2; entity.Failure3 = string.IsNullOrEmpty(item.Desc_ID_Falla3) ? "" : item.Desc_ID_Falla3; entity.FailureID1 = string.IsNullOrEmpty(item.ID_Falla1) ? "" : item.ID_Falla1; entity.FailureID2 = string.IsNullOrEmpty(item.ID_Falla2) ? "" : item.ID_Falla2; entity.FailureID3 = string.IsNullOrEmpty(item.ID_Falla3) ? "" : item.ID_Falla3; entity.FK_ClientID = dataODS.FK_ClientID; entity.FK_InstalledBaseID = dataODS.FK_InstalledBaseID; entity.FK_OrderID = dataODS.PK_OrderID; entity.Guaranty = string.IsNullOrEmpty(item.Tipo_Serv) ? "" : item.Tipo_Serv; entity.ItemStatus = string.IsNullOrEmpty(item.Estatus_Visita) ? "" : item.Estatus_Visita; entity.ModifyDate = DateTime.UtcNow; entity.OrderID = string.IsNullOrEmpty(item.ID_Oper) ? "" : item.ID_Oper; entity.OrderStatus = string.IsNullOrEmpty(item.Estatus_Oper) ? "" : item.Estatus_Oper; entity.PK_HistoryID = 0; entity.ShopDate = new DateTime(1980, 1, 1); entity.Status = true; FacadeHistory.Insert(entity); } } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } j++; } //Inventory(); //RestImage(); //SendEmial(); //foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones()) // Console.WriteLine(z.Id); //Console.WriteLine(FacadeGoogle.GetLocalDateTime(19.3850, -99.1650, DateTime.UtcNow)); //string CLIENT_ID = "6538892993478012"; //string CLIENT_SECRET = "GGGzSZuzfdBDpua7g7wyZo9qiTrnTvcS"; //MP mp = new MP(CLIENT_ID, CLIENT_SECRET); //Hashtable data = mp.getPaymentInfo("9406314591T0170101000525SFODS"); // Sets the filters you want //Dictionary<String, String> filters = new Dictionary<String, String>(); //filters.Add("site_id", "MLM"); // Argentina: MLA; Brasil: MLB // Search payment data according to filters //Hashtable searchResult = mp.searchPayment(filters); // Show payment information //foreach (Hashtable payment in searchResult.SelectToken("response.results")) //{ // Console.WriteLine(String.Format("{0}", payment["collection"]["id"])); //} Console.WriteLine("Finish"); Console.ReadKey(); }
public EntityHistory[] GetSolvedTasks(LotInfoJSON[] data, string startDate, int addMinutes) { List <string> diffList = new List <string>() { "LPN01", "LPN02", "LPN04", "LPP02", "LPP05", "FHT01", "LPT01", "FOX01", "FOX04", "FAL01" }; Funcs funcs = new Funcs(); var date = funcs.StrToDate(startDate); //если передано addMinutes == 25 часов то имеется в виду текущее время if (addMinutes == 25 * 60) { addMinutes = 0; date = DateTime.Now; } //Горизонт событий int horizon = 48 * 60 * 100000; // Creates the model. CpModel model = new CpModel(); // Creates jobs. List <Task> all_tasks = new List <Task>(); //Формирование задач для Солвера foreach (string ent in diffList) { //Задачи одной установки List <LotTask> entityTasks = new List <LotTask>(); foreach (var lot in data) { foreach (var task in lot.Tasks) { if (task.Entity == ent) { entityTasks.Add(task); } } } //Удаляем повторения задач entityTasks = entityTasks.Distinct(new DistinctItemComparer()).ToList(); // Добавляем/дополняем задачи для Солвера foreach (LotTask t in entityTasks) { IntVar start_var = model.NewIntVar(t.Delay, horizon, "Task Start"); int duration = t.Duration; IntVar end_var = model.NewIntVar(0, horizon, "Task End"); IntervalVar interval_var = model.NewIntervalVar( start_var, duration, end_var, String.Join(' ', getLotsFromPaket(data, t.paket))); //String.Format(getLotsFromPaket(data, t.paket) + t.Operation.ToString() + " " + t.Recipe + " " + t.Duration.ToString() + " " + t.Delay)); all_tasks.Add(new Task(start_var, end_var, interval_var, t.Operation, getLotsFromPaket(data, t.paket), t.Entity, t.Recipe, t.paket, getPriority(data, t.Lot), getMaxOperAgo(data, t.Lot), t.Duration)); } } #region Constraints (ограничения, МВХ и условия) /* * // Последовательность запуска задач (согласно № операции) для одной партии * // НЕ ВСЕГДА ВЕРНО!!! * foreach(var lot in data.Select(x => x.Lot).ToList()) * { * var tasks = all_tasks.Where(t => t.lots[0] == lot).ToList().OrderBy(t => t.operation).ToList(); * * for (int t = 1; t < tasks.Count; t++) * model.Add(tasks[t].start >= tasks[t - 1].end); * * }*/ //Назначение приоритетов сортировки по OperAgo & priority foreach (var ent in diffList) { var allEntTasks = all_tasks.Where(e => e.entity == ent).ToList(); if (allEntTasks.Count > 1) { foreach (Task task in allEntTasks) { task.sortPriority = -task.maxOperAgo * 2 + task.priority * 3; // формула расчёта баллов приоритета } allEntTasks = allEntTasks.OrderByDescending(x => x.sortPriority).ToList(); // чем больше приоритет тем раньше старт for (var t0 = 0; t0 < allEntTasks.Count - 1; t0++) { model.Add(allEntTasks[t0].start < allEntTasks[t0 + 1].start); } } } //МВХ захардкожено foreach (var lot in data.Select(x => x.Lot).ToList()) { var tasks = all_tasks.Where(t => t.lots[0] == lot).ToList().OrderBy(t => t.operation).ToList(); var mbx = 14; for (int t = 1; t < tasks.Count; t++) { if (tasks[t].operation == 1015) { mbx = 14; } if (tasks[t].operation == 1120) { mbx = 14; } if (tasks[t].operation == 1350) { mbx = 24; } if (tasks[t].operation == 1380) { mbx = 24; } if (tasks[t].operation == 1390) { mbx = 24; } if (tasks[t].operation == 2280) { mbx = 24; } if (tasks[t].operation == 2292) { mbx = 14; } if (tasks[t].operation == 2390) { mbx = 14; } if (tasks[t].operation == 2410) { mbx = 8; } if (tasks[t].operation == 3270) { mbx = 14; } if (tasks[t].operation == 3280) { mbx = 24; } if (tasks[t].operation == 3390) { mbx = 14; } if (tasks[t].operation == 3410) { mbx = 24; } if (tasks[t].operation == 4520) { mbx = 24; } if (tasks[t].operation == 4560) { mbx = 72; } if (tasks[t].operation == 4960) { mbx = 24; } if (tasks[t].operation == 4990) { mbx = 72; } model.Add(tasks[t].start - tasks[t - 1].end <= mbx); // МВХ 14 часов } } //Ограничение на продувки для FOX01 //Продувки после процесса: После каждого процесса OXIDE16T, OXIDE58TM, OXIDE581TM, OX533TM, // OX531TM, OXIDE70TM, OXPO01C (АЛЬТЕРНАТИВНЫЙ) продувка WET-DCE-CLN - 280 мин var FOX01Tasks = all_tasks.Where(t => t.entity == "FOX01").ToList(); List <string> FOX01Recipies = new List <string>() { "OXIDE16T", "OXIDE58TM", "OXIDE581TM", "OX533TM", "OX531TM", "OXIDE70TM", "OXPO01C" }; for (int t = 0; t < FOX01Tasks.Count; t++) { if (FOX01Recipies.Contains(FOX01Tasks[t].recipe)) { IntVar start_var = model.NewIntVar(0, horizon, "Purge Start"); int duration = 280; IntVar end_var = model.NewIntVar(0, horizon, "Purge End"); IntervalVar interval_var = model.NewIntervalVar(start_var, duration, end_var, "After " + FOX01Tasks[t].recipe + " WET-DCE-CLN 280 min"); var purgeTask = new Task(start_var, end_var, interval_var, 0, new List <string>() { "FOX01 Purge" }, "FOX01", "WET-DCE-CLN", 0, -1, 0, 280); all_tasks.Add(purgeTask); //model.Add(purgeTask.start >= FOX01Tasks[t].end); model.Add(purgeTask.start - FOX01Tasks[t].end < 10); model.Add(purgeTask.start - FOX01Tasks[t].end > 0); } ; } //Ограничение на продувки для LPN02 // До и после обработки NIT1100A, NIT1500A, NITR1500K, NITR01 должна проходить // ОБЯЗАТЕЛЬНО необходимая технологическая продувка 20-CYCLE-PURGE = 200 мин var LPN02Tasks = all_tasks.Where(t => t.entity == "LPN02").ToList(); List <string> LPN02Recipies = new List <string>() { "NIT1100A", "NIT1500A", "NITR1500K", "NITR01" }; //ограничение на продувку после рецепта for (int t = 0; t < LPN02Tasks.Count; t++) { if (LPN02Recipies.Contains(LPN02Tasks[t].recipe)) { IntVar start_var = model.NewIntVar(0, horizon, "Purge Start"); IntVar end_var = model.NewIntVar(0, horizon, "Purge End"); IntervalVar interval_var = model.NewIntervalVar(start_var, 200, end_var, "After " + LPN02Tasks[t].recipe + " 20-CYCLE-PURGE 200 min"); var purgeTaskAfter = new Task(start_var, end_var, interval_var, 0, new List <string> { "Purge After" }, "LPN02", "20-CYCLE-PURGE", 0, -1, 0, 200); all_tasks.Add(purgeTaskAfter); model.Add(purgeTaskAfter.start - LPN02Tasks[t].end < 10); model.Add(purgeTaskAfter.start - LPN02Tasks[t].end > 0); } ; } //ограничение на продувку до рецепта for (int t = 0; t < LPN02Tasks.Count; t++) { if (LPN02Recipies.Contains(LPN02Tasks[t].recipe)) { IntVar start_var = model.NewIntVar(0, horizon, "Purge Start"); IntVar end_var = model.NewIntVar(0, horizon, "Purge End"); IntervalVar interval_var = model.NewIntervalVar(start_var, 200, end_var, "Before " + LPN02Tasks[t].recipe + " 20-CYCLE-PURGE 200 min"); var purgeTaskBefore = new Task(start_var, end_var, interval_var, 0, new List <string> { "Purge Before" }, "LPN02", "20-CYCLE-PURGE", 0, -1, 0, 200); all_tasks.Add(purgeTaskBefore); model.Add(LPN02Tasks[t].start - purgeTaskBefore.end < 10); model.Add(LPN02Tasks[t].start - purgeTaskBefore.end > 0); } ; } //!!!НУЖНО СДЕЛАТЬ!!! Ограничение: запрет 2-х продувок подряд !!!НУЖНО СДЕЛАТЬ!!! //var tasksBefore = all_tasks.Where(b => b.lot == "Purge Before").ToList(); //var tasksAfter = all_tasks.Where(a => a.lot == "Purge After").ToList(); // Ограничение на отсутствие пересечений задач для одной установки foreach (var ent in diffList) { List <IntervalVar> machine_to_jobs = new List <IntervalVar>(); var entTasks = all_tasks.Where(t => (t.entity == ent)).ToList(); for (int j = 0; j < entTasks.Count; j++) { machine_to_jobs.Add(entTasks[j].interval); } model.AddNoOverlap(machine_to_jobs); } var test = all_tasks.Where(t => t.recipe == "MSHTO05").ToList(); // Makespan objective. IntVar[] all_ends = new IntVar[all_tasks.Count]; for (int j = 0; j < all_tasks.Count; j++) { all_ends[j] = all_tasks[j].end; } IntVar makespan = model.NewIntVar(0, horizon, "makespan"); model.AddMaxEquality(makespan, all_ends); model.Minimize(makespan); #endregion // Creates the solver and solve. CpSolver solver = new CpSolver(); //максимальное время расчёта solver.StringParameters = "max_time_in_seconds:" + "40"; solver.Solve(model); #region Преобразование в EntityHistory[] для Gantt chart List <EntityHistory> solvedEntityHistories = new List <EntityHistory>(); DateTime firstDate = new DateTime(1970, 1, 1, 0, 0, 0); long startTime = (long)(date.AddMinutes(addMinutes) - firstDate).TotalSeconds; int id = 0; foreach (var ent in diffList) { var tempEntityHistory = new EntityHistory(); tempEntityHistory.Id = id; tempEntityHistory.Parent = ent; tempEntityHistory.Name = ent + "_план"; var entAllTasks = all_tasks.Where(t => t.entity == ent).ToList(); foreach (Task task in entAllTasks) { LotInfoPeriodGantt per = new LotInfoPeriodGantt(); per.color = getColor(task.priority); per.start = (startTime + solver.Value(task.start) * 60) * 1000 + 120000; per.end = (startTime + solver.Value(task.end) * 60) * 1000 - 120000; per.duration = task.duration; per.id = id; per.lot = task.interval.Name(); per.operation = task.operation.ToString(); per.recipe = task.recipe; per.connectTo = ""; per.connectorType = "finish - start"; tempEntityHistory.Periods.Add(per); id++; } solvedEntityHistories.Add(tempEntityHistory); } #endregion return(solvedEntityHistories.ToArray()); }
public async Task Add(EntityHistory history) { await _dbContext.EntityHistories.AddAsync(history); }
public void Insert(EntityHistory data) { new RepositoryHistory().Insert(data); }
public TaskHistoryViewModel(EntityHistory taskHistory, IQueryService <TaskState> taskStateQueryService) { _taskStateQueryService = taskStateQueryService; CommitChanges = new ObservableCollection <CommitChangesViewModel>(); ResolveTaskHistory(taskHistory); }
private bool ValuesSet(EntityHistory hist) { switch (hist.EntityType.Name) { case "IAccount": IAccount account = EntityFactory.GetById<IAccount>(hist.EntityId.ToString()); Account.LookupResultValue = account; Contact.LookupResultValue = GetPrimaryContact(account.Contacts); return true; case "IContact": IContact contact = EntityFactory.GetById<IContact>(hist.EntityId.ToString()); Contact.LookupResultValue = contact; Account.LookupResultValue = contact.Account; return true; case "IOpportunity": IOpportunity opportunity = EntityFactory.GetById<IOpportunity>(hist.EntityId.ToString()); Opportunity.LookupResultValue = opportunity; Account.LookupResultValue = opportunity.Account; foreach (IOpportunityContact oppContact in opportunity.Contacts) { if (oppContact.IsPrimary.HasValue) { if ((bool)oppContact.IsPrimary) { Contact.LookupResultValue = oppContact.Contact; break; } } } return true; case "ITicket": ITicket ticket = EntityFactory.GetById<ITicket>(hist.EntityId.ToString()); Ticket.LookupResultValue = ticket; Account.LookupResultValue = ticket.Account; Contact.LookupResultValue = ticket.Contact; return true; case "ILead": SetDivVisible(VisibleDiv.Lead); ILead lead = EntityFactory.GetById<ILead>(hist.EntityId.ToString()); LeadId.LookupResultValue = lead; Company.Text = lead.Company; return true; } return false; }