// Recursively get entity states public static IEnumerable <EntityState> GetEntityStates(this DbContext context, ITrackable item, EntityState?entityState = null, ObjectVisitationHelper visitationHelper = null) { // Prevent endless recursion ObjectVisitationHelper.EnsureCreated(ref visitationHelper); if (!visitationHelper.TryVisit(item)) { yield break; } foreach (var colProp in item.GetNavigationProperties().OfCollectionType()) { foreach (ITrackable child in colProp.EntityCollection) { foreach (var state in context.GetEntityStates(child, visitationHelper: visitationHelper)) { if (entityState == null || state == entityState) { yield return(state); } } } } yield return(context.Entry(item).State); }
/// <summary> /// Applies the changes of the entity to the context. /// </summary> /// <param name="entity">The entity to manage.</param> /// <param name="currentState">The original state (optional).</param> /// <param name="targetState">The chosen state.</param> internal void ManageEntity(IEntityObjectIdentifier entity, EntityState?currentState, EntityState targetState) { if (gate.Configuration.CanUseLogging) { gate.Configuration.Log(string.Format(CultureInfo.InvariantCulture, Resources.ChangeEntityToState, entity, targetState)); } if (targetState == EntityState.Detached) { throw new EntityGateProviderException(string.Format(CultureInfo.InvariantCulture, Resources.UnexpectedEntityState, targetState, entity)); } // The current state is not needed for an addition. if (!currentState.HasValue && targetState != EntityState.Added) { currentState = GetEntityState(entity); } // If the entity is detached, check the consistency. if (currentState.HasValue && currentState == EntityState.Detached) { var entityTracked = GetEntityTracked(entity, targetState != EntityState.Deleted); entity = entityTracked ?? entity; } GetEntityEntry(entity).State = targetState; }
protected virtual async Task <T> AddOrModify(T entity, EntityState?state = null) { var serverEntity = AttachEntity(entity, state: state); await db.SaveChangesAsync(); return(serverEntity); }
private async Task GreetIfJustArrived(string entityId, EntityState?to, EntityState?from) { if (entityId.StartsWith("binary_sensor.")) { // The door opened, lets check if someone just arrived var trackerJustArrived = State.Where(n => n.EntityId.EndsWith(PresenceCriteria !) && n.State == "Nyss anlänt"); foreach (var tracker in trackerJustArrived) { await Greet(tracker.EntityId); } } else if (entityId.StartsWith("device_tracker.")) { var dorrSensorState = GetState(DoorSensor !); if (dorrSensorState?.State == "on") { // Door is open, greet await Greet(entityId); } else if (dorrSensorState?.State == "off") { // It is closed, lets check if it was recently opened if (DateTime.Now.Subtract(dorrSensorState.LastChanged) <= TimeSpan.FromMinutes(5)) { // It was recently opened, probably when someone got home await Greet(entityId); } } } }
private async Task VacuumOnSchedule(string entityId, EntityState?newState, EntityState?oldState) { if (!this.AnyoneHome()) { if (GetState(DownstairsScheduler)?.State?.ToString()?.ToLower() == "on") { await CallService("vacuum", "start", new { entity_id = Roborock }); await this.NotifyDiscord(DiscordChannel.Home, "�完 Starting vacuum downstairs."); } if (GetState(UpstairsScheduler)?.State?.ToString()?.ToLower() == "on") { await CallService("vacuum", "start", new { entity_id = Roomba }); await this.NotifyDiscord(DiscordChannel.Home, "�完 Starting vacuum upstairs."); } await Entity(UpstairsScheduler).TurnOff().ExecuteAsync(); await Entity(DownstairsScheduler).TurnOff().ExecuteAsync(); } }
private async Task SetMotionVariables(string entityId, EntityState?to, EntityState?from) { if ((to !.Attribute !.elevation <= 2 && to !.Attribute !.rising == false) || to !.Attribute !.elevation <= -12.0 && to !.Attribute !.rising == true) { await Entity("input_boolean.outdoor_motion_enabled").TurnOn().ExecuteAsync(); }
/// <summary> /// Get index from enum type with optional state. /// </summary> private int GetIndex(TEnum i, EntityState?s = null) { if (s != null) { return(Convert.ToInt32(i) + (_typesCount * (int)s)); } return(Convert.ToInt32(i)); }
public void Attach(T model, EntityState?entityState = null) { _context.Attach(model); if (entityState != null) { _context.Entry(model).State = entityState.Value; } }
/// <summary> /// Get index from enum type with optional state. /// </summary> private int GetIndex(TEnum i, EntityState?s = null) { if (s != null) { return((int)(object)i + (_typesCount * (int)s)); } return((int)(object)i); }
private void EmitPacketEntities(SvClientSnapshot from, SvClientSnapshot to, MsgPacket msg){ EntityState? oldEnt = null; EntityState? newEnt = null; int oldIndex = 0, newIndex = 0; int oldNum, newNum; int fromNumEnts; if(from == null){ fromNumEnts = 0; }else{ fromNumEnts = from.numEntities; } while(newIndex < to.numEntities || oldIndex < fromNumEnts){ if(newIndex >= to.numEntities){ newNum = 9999; }else{ newEnt = snapshotEntities[(to.firstEntity + newIndex) % numSnapshotEntities]; newNum = newEnt.Value.entityIndex; } if(oldIndex >= fromNumEnts){ oldNum = 9999; }else{ oldEnt = snapshotEntities[(from.firstEntity + oldIndex) % numSnapshotEntities]; oldNum = oldEnt.Value.entityIndex; } //相等表示是同一个entity if(newNum == oldNum){ msg.WriteDeltaEntity(oldEnt, newEnt, false); oldIndex++; newIndex++; continue; } //新增的entity排在前面, if(newNum < oldNum){ oldEnt = svEntities[newNum].baseline; msg.WriteDeltaEntity(oldEnt, newEnt, true); oldEnt = null; newIndex++; continue; } //旧的entity消失了,写入一个字段表示此entity消失了 if(newNum > oldNum){ msg.WriteDeltaEntity(oldEnt, null, true); oldIndex++; continue; } } msg.WriteBits(CConstVar.MAX_GENTITIES - 1, CConstVar.GENTITYNUM_BITS); //packet entities尾端 }
public TEntity AttachEntity <TEntity>(TEntity entity, EntityState?withState = null) where TEntity : class { var attachedEntity = _dbContext.Set <TEntity>().Attach(entity); if (withState.HasValue) { _dbContext.Entry(entity).State = withState.Value; } return(attachedEntity); }
public static IEnumerable <EntityState> GetEntityStates(this DbContext context, ITrackable item, EntityState?entityState = null) { var entityStates = new List <EntityState>(); context.TraverseGraph(item, n => { entityStates.Add(n.Entry.State); }); return(entityStates); }
private async Task DoorbellAction(string arg1, EntityState?arg2, EntityState?arg3) { await this.Notify( "Security", "The doorbell has been rung", Notifier.NotificationCriteria.Always, Notifier.NotificationCriteria.None, Notifier.TextNotificationDevice.All); await this.Notify(new Uri("http://192.168.1.2:8123/local/doorbell.mp3"), 1, Notifier.AudioNotificationDevice.Home); }
protected override async Task <User> AddOrModify(User user, EntityState?state = null) { var serverPlayer = user.Player.Id == default(int) ? AttachEntity(user.Player, state: EntityState.Added) : AttachEntity(user.Player); var serverUser = AttachEntity(user, state: state); serverUser.Player = serverPlayer; await db.SaveChangesAsync(); return(serverUser); }
public static IEnumerable <EntityEntry> GetChangedEntities(this DbContext dbContext, EntityState?entityState = null) { var entrise = dbContext.ChangeTracker.Entries(); if (entityState.HasValue) { entrise = entrise.Where(c => c.State == entityState.Value); } return(entrise); }
private async Task DoorOpened(string entityId, EntityState?to, EntityState?from) { await this.NotifyDiscord(DiscordChannel.Home, "Front door opened, checking time."); var doorTime = GetState("sensor.front_door")?.LastUpdated; if (doorTime.HasValue) { await this.NotifyDiscord(DiscordChannel.Home, $"Front door opened at {doorTime.Value}."); Scheduler.RunIn(new TimeSpan(0, 10, 0), async() => await CheckMotion(doorTime.Value)); // Scheduler.RunIn(new TimeSpan(0, 5, 0), async () => await CheckMotion(doorTime.Value)); } }
public bool DoesEntitySupportAMob(int aId) { EntityState entityState = GM.boardManager.GetEntityById(aId); for (int x = entityState.pos.x; x < entityState.pos.x + entityState.size.x; x++) { Vector2Int currentPos = new Vector2Int(x, entityState.pos.y + entityState.size.y + 1); EntityState?maybeAEntity = GM.boardManager.GetEntityAtPos(currentPos); if (maybeAEntity.HasValue && maybeAEntity.Value.mobData?.canFall == true) { return(true); } } return(false); }
void CursorModeSelectingUpdate() { EntityState?maybeAEntity = GM.boardManager.GetEntityAtMousePos(this.isFront); if (maybeAEntity.HasValue) { SetPos(maybeAEntity.Value.pos); SetSize(maybeAEntity.Value.size); } else { SetPos(GM.inputManager.mousePosV2); SetSize(new Vector2Int(1, 1)); } }
public bool TryGetObjectState <TObject>(IKey <TObject> key, out EntityState?state, out TObject entity) where TObject : class { entity = null; state = null; var existingEntity = Context.ChangeTracker.Entries <TObject>().SingleOrDefault(e => key.FindByPredicate.Compile().Invoke(e.Entity)); if (existingEntity == null) { return(false); } entity = existingEntity.Entity; state = existingEntity.State; return(true); }
protected T2 AttachEntity <T2>(T2 entity, bool overrideValues = true, EntityState?state = null) where T2 : class, IEntity { var entry = db.AttachToOrGet(entity); if (overrideValues && entry.Entity != entity) { entry.CurrentValues.SetValues(entity); } if (state != null) { entry.State = state.Value; } return(entry.Entity); }
public static List <object> Serialize(LogEntry entry, EntityState?state, SerializationContext context) { switch (state) { case null: return(new List <object> { entry.Id, ToString(entry) }); case EntityState.Added: return(new List <object> { (int)state, entry.Id, ToString(entry) }); case EntityState.Deleted: return(new List <object> { (int)state, entry.Id }); default: var properties = new List <object> { (int)state, entry.Id }; var logEntry = context.DbContext.Entry(entry); var i = 1; var tick = logEntry.Property(nameof(LogEntry.Tick)); var message = logEntry.Property(nameof(LogEntry.Message)); if (tick.IsModified || message.IsModified) { properties.Add(i); properties.Add(ToString(entry)); } return(properties.Count > 2 ? properties : null); } }
public override bool AddCommand(IReadOnlyModificationCommand modificationCommand) { if (_sqlServerBulkConfiguration.Disabled) { _bulkMode = false; return(_modificationCommandBatch.AddCommand(modificationCommand)); } var state = modificationCommand.EntityState; var bulkMode = false; if ((state == EntityState.Added && _bulkOptions.InsertEnabled) || (state == EntityState.Deleted && _bulkOptions.DeleteEnabled)) { bulkMode = true; } if (!_state.HasValue) { _state = state; _table = modificationCommand.TableName; _schema = modificationCommand.Schema; _bulkMode = bulkMode; } if (bulkMode != _bulkMode) { return(false); } if (!_bulkMode) { return(_modificationCommandBatch.AddCommand(modificationCommand)); } if (_state != modificationCommand.EntityState || _table != modificationCommand.TableName || _schema != modificationCommand.Schema) { return(false); } _commands = _commands.Add(modificationCommand); return(true); }
private void UpdateReferenceMaps( InternalEntityEntry entry, EntityState state, EntityState?oldState) { var entityType = entry.EntityType; var mapKey = entry.Entity ?? entry; if (entityType.HasDefiningNavigation()) { foreach (var otherType in _model.GetEntityTypes(entityType.Name) .Where(et => et != entityType && TryGetEntry(mapKey, et) != null)) { UpdateLogger.DuplicateDependentEntityTypeInstanceWarning(entityType, otherType); } } _entityReferenceMap.Update(entry, state, oldState); }
public void Update() { if (GM.inputManager.mouseState == MouseStateEnum.CLICKED) { EntityState?maybeAEntity = GM.boardManager.GetEntityAtMousePos(GM.editManager.currentState.isFront); if (maybeAEntity.HasValue) { int id = maybeAEntity.Value.id; GM.editManager.SetSelectedEntity(id); } else { GM.editManager.ClearSelectedEntity(); } } if (GM.inputManager.rightMouseState == MouseStateEnum.CLICKED) { GM.editManager.ClearSelectedEntity(); } }
private async Task CleanersArrive(string entityId, EntityState?to, EntityState?from) { if (GetState("calendar.cleaning_day")?.State?.ToString() == "on") { if (!this.AnyoneHome()) { //script cleaner arriving, turn on lights await CallService("script", "1587035537523"); } await CallService("input_boolean", "turn_on", new { entity_id = "input_boolean.ec_lights_on_ring_control" }); await CallService("input_boolean", "turn_off", new { entity_id = "input_boolean.ad_litterboxes" }); await this.NotifyIos("Cleaning time!", "Cleaner has arrived"); } }
public override ActionResult GetActionResult(BoardState aBoardState) { BoardState simBoardState = aBoardState; EntityState simEntityState = simBoardState.GetEntityById(this.id); if (simEntityState.team != TeamEnum.PLAYER) { // Debug.Log(this.id + " ExitAction.GetActionResult tried on non-player entity RETURNING"); return(new ActionResult(this, null)); } // check each occupied pos for a back entity. return null if that back entity isnt an exit foreach (Vector2Int currentPos in Util.V2IInRect(simEntityState.pos, simEntityState.size)) { EntityState?backEntity = simBoardState.GetEntityAtPos(currentPos, false); if (backEntity == null || backEntity.Value.isExit == false) { // Debug.Log(this.id + " ExitAction.GetActionResult done on non exit position RETURNING"); return(new ActionResult(this, null)); } } simBoardState = ApplyAction(simBoardState); return(new ActionResult(this, simBoardState)); }
private async Task CheckPresenceStatus(string entityId, EntityState?newState, EntityState?oldState) { Log("Checking presence for Isa mode!"); if (!this.StefanHome() && this.IsaHome()) { Log("Isa is home and Stefan is not"); var isa_mode = GetState(IsaHomeEntity); if (isa_mode?.State == "off") { Log("Ask about home alone"); await this.NotifyIos("👧🏻 Home alone!", "Turn on mode?", "", false, "isa-mode", "isa_mode"); // await CallService("input_boolean", "turn_on", new // { // entity_id = IsaHomeEntity // }); } else { Log("Isa mode already on"); } } }
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void Update( [NotNull] InternalEntityEntry entry, EntityState state, EntityState?oldState) { var mapKey = entry.Entity ?? entry; var entityType = entry.EntityType; if (_hasSubMap && entityType.HasDefiningNavigation()) { if (_dependentTypeReferenceMap == null) { _dependentTypeReferenceMap = new Dictionary <IEntityType, EntityReferenceMap>(); } if (!_dependentTypeReferenceMap.TryGetValue(entityType, out var dependentMap)) { dependentMap = new EntityReferenceMap(hasSubMap: false); _dependentTypeReferenceMap[entityType] = dependentMap; } dependentMap.Update(entry, state, oldState); } else { if (oldState.HasValue) { Remove(mapKey, entityType, oldState.Value); } if (!oldState.HasValue || state != EntityState.Detached) { switch (state) { case EntityState.Detached: if (_detachedReferenceMap == null) { _detachedReferenceMap = new Dictionary <object, InternalEntityEntry>(ReferenceEqualityComparer.Instance); } _detachedReferenceMap[mapKey] = entry; break; case EntityState.Unchanged: if (_unchangedReferenceMap == null) { _unchangedReferenceMap = new Dictionary <object, InternalEntityEntry>(ReferenceEqualityComparer.Instance); } _unchangedReferenceMap[mapKey] = entry; break; case EntityState.Deleted: if (_deletedReferenceMap == null) { _deletedReferenceMap = new Dictionary <object, InternalEntityEntry>(ReferenceEqualityComparer.Instance); } _deletedReferenceMap[mapKey] = entry; break; case EntityState.Modified: if (_modifiedReferenceMap == null) { _modifiedReferenceMap = new Dictionary <object, InternalEntityEntry>(ReferenceEqualityComparer.Instance); } _modifiedReferenceMap[mapKey] = entry; break; case EntityState.Added: if (_addedReferenceMap == null) { _addedReferenceMap = new Dictionary <object, InternalEntityEntry>(ReferenceEqualityComparer.Instance); } _addedReferenceMap[mapKey] = entry; break; } } } }
private async Task PcNotInUseAction(string arg1, EntityState?arg2, EntityState?arg3) { await Entity(MonitorSwitch !).TurnOff().ExecuteAsync(); }
/// <summary> /// Validates cardinality constraints for all added entities/relationships. /// </summary> internal void ValidateConstraints() { // ensure all expected relationships exist foreach (KeyValuePair <DirectionalRelationship, IEntityStateEntry> expected in m_impliedRelationships) { DirectionalRelationship expectedRelationship = expected.Key; IEntityStateEntry stateEntry = expected.Value; // determine actual end cardinality int count = GetDirectionalRelationshipCountDelta(expectedRelationship); if (EntityState.Deleted == stateEntry.State) { // our cardinality expectations are reversed for delete (cardinality of 1 indicates // we want -1 operation total) count = -count; } // determine expected cardinality int minimumCount = MetadataHelper.GetLowerBoundOfMultiplicity(expectedRelationship.FromEnd.RelationshipMultiplicity); int?maximumCountDeclared = MetadataHelper.GetUpperBoundOfMultiplicity(expectedRelationship.FromEnd.RelationshipMultiplicity); int maximumCount = maximumCountDeclared.HasValue ? maximumCountDeclared.Value : count; // negative value // indicates unlimited cardinality if (count < minimumCount || count > maximumCount) { // We could in theory "fix" the cardinality constraint violation by introducing surrogates, // but we risk doing work on behalf of the user they don't want performed (e.g., deleting an // entity or relationship the user has intentionally left untouched). throw EntityUtil.UpdateRelationshipCardinalityConstraintViolation( expectedRelationship.AssociationSet.Name, minimumCount, maximumCountDeclared, TypeHelpers.GetFullName(expectedRelationship.ToEntityKey.EntityContainerName, expectedRelationship.ToEntityKey.EntitySetName), count, expectedRelationship.FromEnd.Name, stateEntry); } } // ensure actual relationships have required ends foreach (DirectionalRelationship actualRelationship in m_existingRelationships.Keys) { int addedCount; int deletedCount; actualRelationship.GetCountsInEquivalenceSet(out addedCount, out deletedCount); int absoluteCount = Math.Abs(addedCount - deletedCount); int minimumCount = MetadataHelper.GetLowerBoundOfMultiplicity(actualRelationship.FromEnd.RelationshipMultiplicity); int?maximumCount = MetadataHelper.GetUpperBoundOfMultiplicity(actualRelationship.FromEnd.RelationshipMultiplicity); // Check that we haven't inserted or deleted too many relationships if (maximumCount.HasValue) { EntityState?violationType = default(EntityState?); int? violationCount = default(int?); if (addedCount > maximumCount.Value) { violationType = EntityState.Added; violationCount = addedCount; } else if (deletedCount > maximumCount.Value) { violationType = EntityState.Deleted; violationCount = deletedCount; } if (violationType.HasValue) { throw EntityUtil.Update(Strings.Update_RelationshipCardinalityViolation(maximumCount.Value, violationType.Value, actualRelationship.AssociationSet.ElementType.FullName, actualRelationship.FromEnd.Name, actualRelationship.ToEnd.Name, violationCount.Value), null, actualRelationship.GetEquivalenceSet().Select(reln => reln.StateEntry)); } } // We care about the case where there is a relationship but no entity when // the relationship and entity map to the same table. If there is a relationship // with 1..1 cardinality to the entity and the relationship is being added or deleted, // it is required that the entity is also added or deleted. if (1 == absoluteCount && 1 == minimumCount && 1 == maximumCount) // 1..1 relationship being added/deleted { bool isAdd = addedCount > deletedCount; // Ensure the entity is also being added or deleted IEntityStateEntry entityEntry; // Identify the following error conditions: // - the entity is not being modified at all // - the entity is being modified, but not in the way we expect (it's not being added or deleted) if (!m_impliedRelationships.TryGetValue(actualRelationship, out entityEntry) || (isAdd && EntityState.Added != entityEntry.State) || (!isAdd && EntityState.Deleted != entityEntry.State)) { throw EntityUtil.UpdateEntityMissingConstraintViolation(actualRelationship.AssociationSet.Name, actualRelationship.ToEnd.Name, actualRelationship.StateEntry); } } } }