public void UpdateTrackedEntity(ParsedMessage pm, bool selfcalled) { TrackedEntity te = trackedEntities.Where(x => x.EntityID == pm.TargetEntityId).FirstOrDefault(); if (te == null) { te = new TrackedEntity(pm, log); trackedEntities.Add(te); } te.Location = pm.Location; te.Velocity = pm.Velocity; te.LastUpdated = DateTime.Now; te.Radius = pm.TargetRadius; te.DetailsString = pm.ToString(); te.Relationship = pm.Relationship; if (pm.AttackPoint != Vector3D.Zero) { te.UpdatePoints(new PointOfInterest(pm.AttackPoint)); } if (selfcalled) { te.UpdateNearestPoints(new PointOfInterest(pm.AttackPoint), cubeGrid.GetPosition()); } }
public void UpdateSurfaceLocation(TrackedEntity pm) { //log.Debug("initial location to save: "+ pm.AttackPoint); var point = new PointOfInterest(pm.AttackPoint, pm.EntityID); //log.Debug(pm.AttackPoint+""); PlanetaryData planet = KnownPlanets.FirstOrDefault(x => x.PlanetCenter == pm.Location); Region region = null; region = new Region(pm.EntityID, pm.Location, point, iscmd, cubeGrid.GetPosition(), log); if (planet != null) { planet.UpdatePlanetaryData(region, cubeGrid.GetPosition()); } //if no planet if (planet == null) { planet = CreateNewPlanet(pm.EntityID, pm.Location, region, point, cubeGrid.GetPosition()); //if point is in current region, update region if (currentRegion.EntityId == pm.EntityID) { currentRegion.UpdatePoints(point); } //if point in another region, increase its scan density //log.Debug("Number of regions: " + nearestPlanet.Regions.Count); } if (KnownPlanets.Count > 1) { nearestPlanet = KnownPlanets.OrderBy(x => (x.PlanetCenter - pm.Location).Length()).FirstOrDefault(); } }
protected void ScanWithCameras(Dictionary <long, TrackedEntity> foundentities) { if (cameraIndex == shipComponents.Cameras.Count()) { cameraIndex = 0; } var camera = shipComponents.Cameras[cameraIndex]; var maxAngle = maxCameraAngle; //== 0 ? camera.RaycastConeLimit : maxCameraAngle; var maxRange = maxCameraRange; //== 0? camera.RaycastDistanceLimit: maxCameraRange; if (!camera.EnableRaycast) { camera.EnableRaycast = true; } var timeToScan = camera.TimeUntilScan(range); if (timeToScan <= 0 && cameraIndex < shipComponents.Cameras.Count()) { pitch -= 5; if (pitch <= -maxAngle) { pitch = pitch * -1; yaw -= 5; //log.Debug("flipping pitch"); } if (yaw <= -maxAngle) { yaw = yaw * -1; range -= 200; //log.Debug("flipping yaw"); } if (range <= 1) { range = maxCameraRange; // log.Debug("flipping range"); } //var ent = camera.Raycast(range, pitch, yaw); var ent = camera.Raycast(range, pitch, yaw); //log.Debug("Scanning Raycast: \nrange:pitch:yaw " + range + ":" + pitch + ":" + yaw); if (ent.EntityId != 0) { if (!foundentities.Keys.Contains(ent.EntityId)) { var t = new TrackedEntity(ent.Position, ent.Velocity, ent.HitPosition.Value, ent.EntityId, ent.Name, (int)Math.Abs((ent.BoundingBox.Min - ent.BoundingBox.Max).Length()), ent.Relationship, ent.HitPosition.Value, ent.Type.ToString(), log); //log.Debug("initial camera points: "+ ent.HitPosition.Value +": "+ ent.Position); foundentities.Add(ent.EntityId, t); } } } cameraIndex++; }
public void detect_changes_negative() { var target = Target.Random(); var entity = new TrackedEntity(target.Id, new TestsSerializer(), typeof(Target), target, null); SpecificationExtensions.ShouldBeNull(entity.DetectChange()); }
public void multi_tenancy_test_to_excercise_the_service_arguments() { var tenantA = Guid.NewGuid(); var tenantB = Guid.NewGuid(); var trackedA1 = new TrackedEntity(); var trackedA2 = new TrackedEntity(); var trackedB1 = new TrackedEntity(); var trackedB2 = new TrackedEntity(); var trackedB3 = new TrackedEntity(); var repo = theUnitOfWork.Start(tenantA); repo.Update(trackedA1); repo.Update(trackedA2); theUnitOfWork.Commit(); repo = theUnitOfWork.Start(tenantB); repo.Update(trackedB1); repo.Update(trackedB2); repo.Update(trackedB3); theUnitOfWork.Commit(); theUnitOfWork.Start(tenantA) .All <TrackedEntity>().ShouldHaveTheSameElementsAs(trackedA1, trackedA2); theUnitOfWork.Reject(); theUnitOfWork.Start(tenantB) .All <TrackedEntity>().ShouldHaveTheSameElementsAs(trackedB1, trackedB2, trackedB3); theUnitOfWork.Reject(); }
protected override async Task <Models.User> BindUser(RegisterMusicianRequest requestBody, DateTime creationDate) { return(await Task.Run(() => new Musician() { _id = ObjectId.GenerateNewId(creationDate), StartDate = ValidationUtils.ValidateBornDate(requestBody.Nascimento), Email = ValidationUtils.ValidateEmail(requestBody.Email), EmailConfirmed = false, Address = new Address() { City = requestBody.Cidade, State = EnumExtensions.FromShortDisplayName <BrazilState>(requestBody.Uf), }, Phone = ValidationUtils.ValidatePhoneNumber(requestBody.Telefone), Ip = TrackedEntity <IPAddress> .From(HttpContext.Connection.RemoteIpAddress, creationDate), TrackedPosition = TrackedEntity <GeoJsonPoint <GeoJson3DGeographicCoordinates> > .From(null, creationDate), FullName = ValidationUtils.ValidateName(requestBody.NomeCompleto), Password = Encryption.Encrypt(ValidationUtils.ValidatePassword(requestBody.Senha)), PremiumLevel = PremiumLevel.None, Avatar = null, InstrumentSkills = requestBody.Instrumentos?.DefaultIfEmpty().Where(instr => instr != null).ToDictionary(instr => EnumExtensions.FromDisplayName <Skill>(instr.Nome), el => (SkillLevel)el.NivelHabilidade).ToHashSet(), Works = new HashSet <Models.Work>(), Songs = new HashSet <Models.Song>(), About = requestBody.Sobre, Visits = 0 })); }
public void detect_changes_negative() { var target = Target.Random(); var entity = new TrackedEntity(target.Id, new JilSerializer(), typeof(Target), target); entity.DetectChange().ShouldBeNull(); }
protected override async Task <Models.User> BindUser(RegisterContractorRequest requestBody, DateTime creationDate) { return(await Task.Run(() => new Contractor() { _id = ObjectId.GenerateNewId(creationDate), StartDate = ValidationUtils.ValidateStartDate(requestBody.Inauguracao), Email = ValidationUtils.ValidateEmail(requestBody.Email), EmailConfirmed = false, Address = new Address() { City = requestBody.Cidade, State = EnumExtensions.FromShortDisplayName <BrazilState>(requestBody.Uf), Road = requestBody.Endereco, Numeration = requestBody.Numero, }, Phone = ValidationUtils.ValidatePhoneNumber(requestBody.Telefone), Ip = TrackedEntity <IPAddress> .From(HttpContext.Connection.RemoteIpAddress, creationDate), TrackedPosition = TrackedEntity <GeoJsonPoint <GeoJson3DGeographicCoordinates> > .From(null, creationDate), FullName = ValidationUtils.ValidateName(requestBody.NomeCompleto), Password = Encryption.Encrypt(ValidationUtils.ValidatePassword(requestBody.Senha)), PremiumLevel = PremiumLevel.None, Avatar = null, About = requestBody.Sobre, Visits = 0 })); }
public bool DetachTracked(TrackedEntity tracked) { if (tracked == null) { return(true); } return(trackedEntities.Remove(tracked.EntityRaw)); }
public void Revert(object entity) { TrackedEntity ent = null; if (trackedEntities.TryGetValue(entity, out ent)) { ent.Revert(); } }
public void ResetTracked(TrackedEntity tracked) { if (tracked == null) { return; } if (!tracked.Reset()) { DetachTracked(tracked); } }
public void DeleteTracked(TrackedEntity tracked) { if (tracked == null) { return; } if (tracked.Delete()) { DetachTracked(tracked); } }
public void TrackEntity(TrackedEntity pm, bool selfcalled) { if (!pm.Name.ToLower().Contains("planet")) { UpdateTrackedEntity(pm); } if (pm.Name.ToLower().Contains("planet")) { UpdateSurfaceLocation(pm); } }
public void change_is_cleared() { var target = Target.Random(); var entity = new TrackedEntity(target.Id, new TestsSerializer(), typeof(Target), target, null); target.Long++; var change = entity.DetectChange(); change.ChangeCommitted(); SpecificationExtensions.ShouldBeNull(entity.DetectChange()); }
public void change_is_cleared() { var target = Target.Random(); var entity = new TrackedEntity(target.Id, new JilSerializer(), typeof(Target), target); target.Long++; var change = entity.DetectChange(); change.ChangeCommitted(); entity.DetectChange().ShouldBeNull(); }
public void SaveEntityTrackingFlag(EntityType type, int entityId, bool track) { var trackedEntity = new TrackedEntity(type, entityId); if (track) { this.storage.AddTrackedEntityIfMissing(trackedEntity); } else { this.storage.RemoveTrackedEntity(trackedEntity); } }
public void detect_changes_positive() { var target = Target.Random(); var entity = new TrackedEntity(target.Id, new JilSerializer(), typeof(Target), target); target.Long++; var change = entity.DetectChange(); change.ShouldNotBeNull(); change.DocumentType.ShouldBe(typeof(Target)); change.Id.ShouldBe(target.Id); change.Json.ShouldBe(new JilSerializer().ToJson(target)); }
public void SetPropertiesCorrectly() { var item = new TrackedEntity() { Name = "Hello World" }; _user.CurrentUser = ExampleUserInformationProvider.Users.JohnSmith; var cid = (int)_user.CurrentUser; var cnm = _user.CurrentUser.ToString(); Assert.Null(item.CreatedBy); Assert.Equal(default, item.CreatedAt);
/// <summary> /// Retrieve an entity with a lock for use. /// </summary> /// <param name="id">The ID of the requested entity.</param> /// <param name="createOnMissing">Whether to create a new tracking instance if the entity is not already tracked.</param> /// <returns>An <see cref="ItemUsage{T}"/> which allows reading or writing the item. This should be disposed after usage.</returns> /// <exception cref="KeyNotFoundException">Thrown if <see cref="createOnMissing"/> was false and the item is not in a tracked state.</exception> public async Task <ItemUsage <T> > GetForUse(long id, bool createOnMissing = false) { int retryCount = 10; while (retryCount-- > 0) { TrackedEntity?item; lock (entityMapping) { if (!entityMapping.TryGetValue(id, out item)) { if (!createOnMissing) { DogStatsd.Increment($"{statsDPrefix}.get-notfound"); throw new KeyNotFoundException($"Attempted to get untracked entity {typeof(T)} id {id}"); } entityMapping[id] = item = new TrackedEntity(id, this); DogStatsd.Gauge($"{statsDPrefix}.total-tracked", entityMapping.Count); DogStatsd.Increment($"{statsDPrefix}.create"); } } try { await item.ObtainLockAsync(); } // this may be thrown if the item was destroyed between when we retrieved the item usage and took the lock. catch (InvalidOperationException) { // if we're looking to create on missing, we should retry the whole process now that we are aware a previous tracked instance was destroyed. if (createOnMissing) { continue; } // if we're just looking to retrieve and instance, to an external consumer, this should just be handled as the item not being tracked. DogStatsd.Increment($"{statsDPrefix}.get-notfound"); throw new KeyNotFoundException($"Attempted to get untracked entity {typeof(T)} id {id}"); } DogStatsd.Increment($"{statsDPrefix}.get"); return(new ItemUsage <T>(item)); } throw new TimeoutException("Could not allocate new entity after multiple retries. Something very bad has happened"); }
protected void ScanWithSensors(Dictionary <long, TrackedEntity> foundentities) { if (sensorindex == shipComponents.Sensors.Count()) { sensorindex = 0; } var miliseconds = (DateTime.Now - lastReportTime).TotalMilliseconds; if (miliseconds >= 1000 / sensorScansPerSecond && sensorindex < shipComponents.Sensors.Count()) { lastReportTime = DateTime.Now; var sensor = shipComponents.Sensors[sensorindex]; sensor.DetectEnemy = true; sensor.DetectPlayers = true; sensor.DetectLargeShips = true; sensor.DetectSmallShips = true; sensor.DetectOwner = false; sensor.DetectStations = true; sensor.DetectAsteroids = true; var ent = sensor.LastDetectedEntity; if (ent.EntityId != 0) { //communicationSystems.SendMessage(EntityInformation); if (!foundentities.Keys.Contains(ent.EntityId)) { //var t = new TrackedEntity(ent.Position, ent.Velocity, ent.HitPosition.Value, ent.EntityId, ent.Name, 0, ent.Relationship, ent.HitPosition.Value, ent.Type.ToString(), log); var t = new TrackedEntity( ent.Position , ent.Velocity , ent.Position , ent.EntityId , ent.Name , 0 , ent.Relationship , ent.Position , ent.Type.ToString() , log);; foundentities.Add(ent.EntityId, t); } } } sensorindex++; }
public void Delete <T>(T entity, string keyName = null) where T : class { if (entity == null) { return; } TrackedEntity <T> t = Get <T>(entity); if (t == null) { t = Add <T>(entity, false, keyName: keyName); } if (t.Delete(keyName)) { DetachTracked(t); } }
public TrackedEntity <T> Add <T>(T entity, bool isNew, bool takeSnapshot = true, string keyName = null) where T : class { if (entity == null) { return(null); } TrackedEntity <T> t = Get <T>(entity); if (t == null) { t = new TrackedEntity <T>(this, entity, isNew, takeSnapshot, keyName); trackedEntities.Add(entity, t); } else { t.ReAdd(isNew); } return(t); }
public void multi_tenancy_test_to_excercise_the_service_arguments() { var tenantA = Guid.NewGuid(); var tenantB = Guid.NewGuid(); var trackedA1 = new TrackedEntity(); var trackedA2 = new TrackedEntity(); var trackedB1 = new TrackedEntity(); var trackedB2 = new TrackedEntity(); var trackedB3 = new TrackedEntity(); transaction.WithRepository(tenantA, repo => { repo.Update(trackedA1); repo.Update(trackedA2); }); transaction.WithRepository(tenantB, repo => { repo.Update(trackedB1); repo.Update(trackedB2); repo.Update(trackedB3); }); transaction.Execute <IDocumentSession>(session => session.Query <TrackedEntity>().Customize(x => x.WaitForNonStaleResults()).Any().ShouldBeTrue()); transaction.WithRepository(tenantA, repo => { repo.All <TrackedEntity>().ShouldHaveTheSameElementsAs(trackedA1, trackedA2); }); bool wasCalled = false; transaction.WithRepository(tenantB, repo => { wasCalled = true; repo.All <TrackedEntity>().ShouldHaveTheSameElementsAs(trackedB1, trackedB2, trackedB3); }); wasCalled.ShouldBeTrue(); }
private void Update() { if (!DoTracking) { m_Icon.enabled = m_LeftArrow.enabled = m_RightArrow.enabled = false; return; } float unitsHeight = Camera.main.orthographicSize * 2f; float aspectRatio = (float)Screen.width / (float)Screen.height; float unitsWidth = unitsHeight * aspectRatio; Vector3 pos = TrackedEntity.GetPosition(); bool outOfBounds = !(pos.x > -unitsWidth * .5f && pos.x < unitsWidth * .5f); m_Icon.enabled = outOfBounds; //Anchor marker based on where entity is offscreen if (m_Icon.enabled) { float screenPosX = unitsWidth * .5f - 1f; if (pos.x < unitsWidth * .5f) { screenPosX = -unitsWidth * .5f + 1f; } transform.position = new Vector3(screenPosX, transform.position.y, transform.position.z); m_LeftArrow.enabled = TrackedEntity.GetTrackingDir() == -1; m_RightArrow.enabled = TrackedEntity.GetTrackingDir() == 1; } else { m_LeftArrow.enabled = m_RightArrow.enabled = false; } }
public void UpdateTrackedEntity(TrackedEntity pm) { var id = pm.EntityID; TrackedEntity existing = trackedEntities.Where(x => x.EntityID == id).FirstOrDefault(); if (existing == null) { existing = pm; trackedEntities.Add(pm); } existing.Location = pm.Location; existing.Velocity = pm.Velocity; existing.LastUpdated = DateTime.Now; existing.Radius = pm.Radius; existing.Relationship = pm.Relationship; if (pm.AttackPoint != Vector3D.Zero) { existing.UpdatePoints(new PointOfInterest(pm.AttackPoint, 0)); } }
public void ShouldProperlyGetTrackEntityViewModelInstanceIfUserWasDeleted() { IMapper mapper = GetMapper(); var trackedEntity = new TrackedEntity { CreatedBy = null, CreatedByName = "Test user", UpdatedBy = null, UpdatedAt = DateTimeOffset.Now, UpdatedByName = "Test user" }; var trackedEntityViewModel = mapper.Map <TrackedEntityViewModel>(trackedEntity); Assert.NotNull(trackedEntityViewModel); Assert.Equal(trackedEntity.CreatedBy, trackedEntityViewModel.CreatedBy); Assert.Equal($"{trackedEntity.CreatedByName} (удален)", trackedEntityViewModel.CreatedByName); Assert.Equal(trackedEntity.UpdatedBy, trackedEntityViewModel.UpdatedBy); Assert.Equal($"{trackedEntity.UpdatedByName} (удален)", trackedEntityViewModel.UpdatedByName); Assert.Equal(trackedEntity.UpdatedAt.Value.ToUnixTimeSeconds(), trackedEntityViewModel.UpdatedAt); }
public void ShouldProperlyGetTrackEntityViewModelInstanceV2() { IMapper mapper = GetMapper(); var trackedEntity = new TrackedEntity { CreatedBy = 22, CreatedByName = "Test user", UpdatedAt = DateTimeOffset.Now, UpdatedBy = 22, UpdatedByName = "Test user" }; var trackedEntityViewModel = mapper.Map <Models.v2.TrackedEntityViewModel>(trackedEntity); Assert.NotNull(trackedEntityViewModel); Assert.Equal(trackedEntity.CreatedBy, trackedEntityViewModel.CreatedBy); Assert.Equal(trackedEntity.CreatedByName, trackedEntityViewModel.CreatedByName); Assert.Equal(trackedEntity.UpdatedBy, trackedEntityViewModel.UpdatedBy); Assert.Equal(trackedEntity.UpdatedByName, trackedEntityViewModel.UpdatedByName); Assert.Equal(trackedEntity.UpdatedAt.Value, trackedEntityViewModel.UpdatedAt); }
protected override async Task <Contractor> BindUser(EditContractorRequest requestBody, DateTime creationDate) { return(await Task.Run(() => new Contractor() { StartDate = ValidationUtils.ValidateStartDate(requestBody.Inauguracao), Email = ValidationUtils.ValidateEmail(requestBody.Email), EmailConfirmed = false, Address = new Address() { City = requestBody.Cidade, State = EnumExtensions.FromShortDisplayName <BrazilState>(requestBody.Uf), Road = requestBody.Endereco, Numeration = requestBody.Numero, }, Phone = ValidationUtils.ValidatePhoneNumber(requestBody.Telefone), Ip = TrackedEntity <IPAddress> .From(HttpContext.Connection.RemoteIpAddress, creationDate), FullName = ValidationUtils.ValidateName(requestBody.NomeCompleto), Password = string.IsNullOrWhiteSpace(requestBody.Senha) ? null : Encryption.Encrypt(ValidationUtils.ValidatePassword(requestBody.Senha)), PremiumLevel = PremiumLevel.None, Avatar = null, About = requestBody.Sobre, })); }
public void multi_tenancy_test_to_excercise_the_service_arguments() { var tenantA = Guid.NewGuid(); var tenantB = Guid.NewGuid(); var trackedA1 = new TrackedEntity(); var trackedA2 = new TrackedEntity(); var trackedB1 = new TrackedEntity(); var trackedB2 = new TrackedEntity(); var trackedB3 = new TrackedEntity(); transaction.WithRepository(tenantA, repo => { repo.Update(trackedA1); repo.Update(trackedA2); }); transaction.WithRepository(tenantB, repo => { repo.Update(trackedB1); repo.Update(trackedB2); repo.Update(trackedB3); }); transaction.WithRepository(tenantA, repo => { repo.All <TrackedEntity>().ShouldHaveTheSameElementsAs(trackedA1, trackedA2); }); bool wasCalled = false; transaction.WithRepository(tenantB, repo => { wasCalled = true; repo.All <TrackedEntity>().ShouldHaveTheSameElementsAs(trackedB1, trackedB2, trackedB3); }); wasCalled.ShouldBeTrue(); }
public void Put(LocationRequest locationRequest) { var userId = new ObjectId(this.GetCurrentUserId()); var userCollection = MongoWrapper.Database.GetCollection <Models.User>(nameof(User)); var userFilterBuilder = new FilterDefinitionBuilder <Models.User>(); var userFilter = userFilterBuilder.And( GeneralUtils.NotDeactivated(userFilterBuilder), userFilterBuilder.Eq(u => u._id, userId) ); var userUpdateBuilder = new UpdateDefinitionBuilder <Models.User>(); var userUpdate = userUpdateBuilder.Set ( u => u.TrackedPosition, TrackedEntity <GeoJsonPoint <GeoJson3DGeographicCoordinates> > .From ( new GeoJsonPoint <GeoJson3DGeographicCoordinates> ( new GeoJson3DGeographicCoordinates(locationRequest.Latitude, locationRequest.Longitude, locationRequest.Altitude) ) ) ); // Do not await the update before returning, only log in case of error var updateResult = userCollection .UpdateOneAsync(userFilter, userUpdate) .ContinueWith ( t => Logger.LogError(t.Exception, "Error while updating user location for user {}", userId), TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously ); Response.StatusCode = (int)HttpStatusCode.OK; }
/// <summary> /// Determines the state. /// </summary> private void DetermineState(TrackedEntity trackedEntity) { if (trackedEntity.State != TrackedEntityState.PossiblyModified) return; var document = new EntityToDocumentMapper(this.mongoSession) .CreateDocument(trackedEntity.Current); if (trackedEntity.Original == null) { //we need to do something else, like check ids against unsaved and what-not throw new NotImplementedException(); } if (!AreDocumentsEqual(document, trackedEntity.Original)) trackedEntity.State = TrackedEntityState.Modified; }
/// <summary> /// Gets the tracked entity, or creates one if it does not exist. /// </summary> /// <param name="entity">The entity.</param> /// <returns></returns> public ITrackedEntity GetTrackedEntity(object entity) { if (entity == null) throw new ArgumentNullException("entity"); var trackedEntity = this.trackedEntities.FirstOrDefault(x => Object.Equals(x.Current, entity)); if(trackedEntity == null) { trackedEntity = new TrackedEntity() { Current = entity }; this.trackedEntities.Add(trackedEntity); } return trackedEntity; }