Пример #1
0
        static void Main(string[] args)
        {
            RootEntity root = new RootEntity();

            int frameRate         = root.GetChild <DataReaderEntity>().GetYAMLObject(@"YAML\ServerConfig.yml").GetData <int>("FrameRate");
            int frameMilliseconds = 1000 / frameRate;

            Stopwatch stopwatch = new Stopwatch();
            int       overTime  = 0;

            while (true)
            {
                stopwatch.Restart();

                root.Step((frameMilliseconds + overTime) * 0.001f);

                stopwatch.Stop();
                int stepTime = (int)stopwatch.ElapsedMilliseconds;

                if (stepTime <= frameMilliseconds)
                {
                    Thread.Sleep(frameMilliseconds - stepTime);
                    overTime = 0;
                }
                else
                {
                    overTime = stepTime - frameMilliseconds;
                }
            }
        }
Пример #2
0
        public void StatusUtility_IsModified_WithMultiLevelHirachy_ShouldGetStatus()
        {
            var rootEntity  = new RootEntity();
            var leafEntityA = new LeafEntity();

            rootEntity.LeafEntities.Add(leafEntityA);
            var leafEntityB = new LeafEntity();

            rootEntity.LeafEntities.Add(leafEntityB);
            var leafEntityNotNull = new LeafEntity();

            rootEntity.LeafEntityNotNull = leafEntityNotNull;
            rootEntity.LeafEntityNull    = null;

            bool unModifiedRoot = StatusManager.IsModified(rootEntity);

            rootEntity.Status = EntityStatus.Modified;
            bool modifiedRoot = StatusManager.IsModified(rootEntity);

            rootEntity.Status  = EntityStatus.Unmodified;
            leafEntityA.Status = EntityStatus.New;
            bool modifiedLeafCollection = StatusManager.IsModified(rootEntity);

            leafEntityA.Status       = EntityStatus.Unmodified;
            leafEntityNotNull.Status = EntityStatus.Deleted;
            bool modifiedLeafSubEntity = StatusManager.IsModified(rootEntity);

            Assert.IsFalse(unModifiedRoot);
            Assert.IsTrue(modifiedRoot);
            Assert.IsTrue(modifiedLeafCollection);
            Assert.IsTrue(modifiedLeafSubEntity);
        }
Пример #3
0
        /// <summary>
        /// Chaining method for adding an obstacle to this Section.
        /// It initializes bounding boxes and stores in Collidable Obstacles.
        /// </summary>
        /// <param name="obstacleEntity">The entity containing the obstacle</param>
        /// <param name="useSubBoundingBoxes">true to use the bounding boxes of the sub-meshes</param>
        /// <returns></returns>
        public Section AddObstacleEntity(Entity obstacleEntity, bool useSubBoundingBoxes)
        {
            // Attach it in ModelEntity
            RootEntity.AddChild(obstacleEntity);

            // Get and add bb to CollidableObstacles
            var modelComponent = obstacleEntity.Get <ModelComponent>();

            var collidableObstacle = new Obstacle {
                Entity = obstacleEntity
            };

            if (useSubBoundingBoxes)
            {
                // Use bounding boxes from parts of the obstacle.
                foreach (var mesh in modelComponent.Model.Meshes)
                {
                    collidableObstacle.BoundingBoxes.Add(mesh.BoundingBox);
                }
            }
            else
            {
                // Use bounding box of the whole model
                collidableObstacle.BoundingBoxes.Add(modelComponent.Model.BoundingBox);
            }

            CollidableObstacles.Add(collidableObstacle);

            return(this);
        }
Пример #4
0
        public void PatchEmpty_PatchDataBase_WithEmptyDb_ShouldCreateTables_ShouldBeAbleToInsertData()
        {
            try
            {
                ITransaction transaction = CreateTransaction();

                int        id     = 36;
                RootEntity entity = CreateRootEntityWithoutNullValues(id);
                entity.LeafEntities.Add(CreateLeafEntityA(id, 1));
                entity.LeafEntities.Add(CreateLeafEntityB(id, 2));
                entity.Persist(transaction);
                transaction.Commit();

                transaction = CreateTransaction();
                RootEntity loadedEntity = LoadRootEntityWithId(transaction, id);
                transaction.Commit();

                AssertTwoRootEntitiesEquals(entity, loadedEntity);
            }
            catch (System.Exception e)
            {
                LogManager.GetLogger(typeof(DbGatePatchEmptyDbTests)).Fatal("Exception during test", e);
                Assert.Fail(e.Message);
            }
        }
Пример #5
0
        public TestQuery(RootEntity root)
        {
            Field(
                typeof(RootType),
                "root",
                "",
                new QueryArguments(),
                context =>
            {
                var query = new List <RootEntity> {
                    root
                }.AsQueryable();

                return(Resolve.SingleObject <RootEntity, RootDto>(query, context));
            });

            Field(
                typeof(ListGraphType <ChildType>),
                "children",
                "",
                new QueryArguments(),
                context =>
            {
                var query = root.Other.Children.AsQueryable();

                return(Resolve.List <ChildEntity, ChildDto>(query, context));
            });
        }
Пример #6
0
        private RootEntity CreateRootEntityWithoutNullValues(int id)
        {
            RootEntity entity = new RootEntity();

            entity.IdCol = id;

            entity.BooleanNotNull   = true;
            entity.BooleanNull      = true;
            entity.CharNotNull      = 'A';
            entity.CharNull         = 'B';
            entity.DateNotNull      = DateTime.Now.AddYears(1);
            entity.DateNull         = DateTime.Now.AddMonths(1);
            entity.DoubleNotNull    = 5D;
            entity.DoubleNull       = 6D;
            entity.FloatNotNull     = 20F;
            entity.FloatNull        = 20F;
            entity.IntNotNull       = 24;
            entity.IntNull          = 23;
            entity.LongNotNull      = 356L;
            entity.LongNull         = 326L;
            entity.TimestampNotNull = DateTime.Now.AddHours(1);
            entity.TimestampNull    = DateTime.Now.AddMinutes(1);
            entity.VarcharNotNull   = "notNull";
            entity.VarcharNull      = "null";

            return(entity);
        }
Пример #7
0
 /// <summary>
 /// Applies the impact.
 /// </summary>
 /// <param name="_direction">Direction.</param>
 /// <param name="_force">Force.</param>
 /// <param name="_point">Point.</param>
 public virtual void ApplyImpact(Vector3 _direction, float _force, Vector3 _point)
 {
     if (IsChildEntity)
     {
         RootEntity.ApplyImpact(_direction, _force);
     }
     else if (ObjectRigidbody != null && !ObjectRigidbody.isKinematic)
     {
         if (_point == Vector3.zero)
         {
             ObjectRigidbody.AddForce(_direction.normalized * _force, ForceMode.Impulse);
         }
         else
         {
             ObjectRigidbody.AddForceAtPosition(_direction.normalized * _force, _point, ForceMode.Impulse);
         }
     }
     else
     {
         _direction.Normalize();
         if (_direction.y < 0)
         {
             _direction.y = -_direction.y;                     // reflect down force on the ground
         }
         m_ImpactForce += _direction.normalized * _force / Mass;
     }
 }
        public void CreateRootEntity()
        {
            using (var persistenceContext = PersistenceHelper.CreatePersistenceContext())
            {
                RootEntity rootEntity = new RootEntity();
                rootEntity.Name = "First Root Entity";

                rootEntity.SaveOrUpdate();
            }
        }
Пример #9
0
 public static void Register(RootEntity rpc)
 {
     rpc.Register(typeof(UIElement), typeof(UIElementFacet));
     rpc.Register(typeof(TextBlock), typeof(TextBlockFacet));
     rpc.Register(typeof(Button), typeof(ButtonFacet));
     rpc.Register(typeof(TreeView), typeof(TreeViewFacet));
     rpc.Register(typeof(CheckBox), typeof(CheckBoxFacet));
     rpc.Register(typeof(ToggleSwitch), typeof(ToggleSwitchFacet));
     rpc.Register(typeof(TextBox), typeof(TextBoxFacet));
 }
Пример #10
0
        public Section AddBackgroundEntity(Entity backgroundEntity)
        {
            // Attach  it in ModelEntity
            RootEntity.AddChild(backgroundEntity);

            // Get length via its bounding box
            var modelComponent = backgroundEntity.Get <ModelComponent>().Model;
            var boundingBox    = modelComponent.BoundingBox;

            Length += boundingBox.Maximum.Z - boundingBox.Minimum.Z;

            return(this);
        }
        public void Update(GameTime gameTime)
        {
            if (!IsActive)
            {
                return;
            }

            // Get Delta Time
            float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;

            // Update
            RootEntity.Update(dt);
            RootEntity.PostUpdate(dt);
        }
Пример #12
0
        public void PatchEmpty_PatchDataBase_WithEmptyDb_ShouldCreatePrimaryKeys_ShouldNotAbleToPutDuplicateData()
        {
            ITransaction transaction = CreateTransaction();

            int        id     = 37;
            RootEntity entity = CreateRootEntityWithoutNullValues(id);

            entity.LeafEntities.Add(CreateLeafEntityA(id, 1));
            entity.LeafEntities.Add(CreateLeafEntityB(id, 1));
            Assert.Throws <PersistException>(() => entity.Persist(transaction));

            transaction.Commit();
            transaction.Close();
        }
Пример #13
0
        public void RootEntity_DeleteExistingChild_StateShould()
        {
            // Arrange
            var root = new RootEntity(new ChildEntity());

            Assert.Equal(State.Unchanged, root.State);
            Assert.Equal(State.Unchanged, root.ChildEntity.State);

            // Act
            root.DeleteChildEntity();

            // Assert
            Assert.Equal(State.Modified, root.State);
            Assert.Null(root.ChildEntity);
        }
Пример #14
0
        public void RootEntity_UpdateChildProperty_StateShould()
        {
            // Arrange
            var root = new RootEntity(new ChildEntity());

            Assert.Equal(State.Unchanged, root.State);
            Assert.Equal(State.Unchanged, root.ChildEntity.State);

            // Act
            root.ChildEntity.SetSimpleField(1);

            // Assert
            Assert.Equal(State.Unchanged, root.State);
            Assert.Equal(State.Modified, root.ChildEntity.State);
        }
Пример #15
0
        public void RootEntity_RemoveExistingChild_StateShould()
        {
            // Arrange
            var root = new RootEntity(new ChildEntity());

            Assert.Equal(State.Unchanged, root.State);
            Assert.Equal(State.Unchanged, root.ChildEntity.State);

            // Act
            var childEntity = root.ChildEntity;

            root.RemoveChildEntity();

            // Assert
            Assert.Equal(State.Modified, root.State);
            Assert.Equal(State.Unchanged, childEntity.State);
            Assert.Null(root.ChildEntity);
        }
Пример #16
0
        /// <summary>
        /// Chaining method for adding an obstacle to this Section.
        /// It initializes bounding boxes and stores in Collidable Obstacles.
        /// </summary>
        /// <param name="obstacleEntity">The entity containing the obstacle</param>
        /// <param name="useSubBoundingBoxes">true to use the bounding boxes of the sub-meshes</param>
        /// <returns></returns>
        public Section AddObstacleEntity(Entity obstacleEntity, bool useSubBoundingBoxes)
        {
            // Attach it in ModelEntity
            RootEntity.AddChild(obstacleEntity);

            // Get and add bb to CollidableObstacles
            var modelComponent = obstacleEntity.Get <ModelComponent>();

            var collidableObstacle = new Obstacle {
                Entity = obstacleEntity
            };

            if (useSubBoundingBoxes)
            {
                // Use bounding boxes from parts of the obstacle.
                foreach (var mesh in modelComponent.Model.Meshes)
                {
                    var boundingBox = mesh.BoundingBox;
                    var nodeIndex   = mesh.NodeIndex;
                    while (nodeIndex >= 0)
                    {
                        var node      = modelComponent.Model.Skeleton.Nodes[nodeIndex];
                        var transform = node.Transform;
                        var matrix    = Matrix.Transformation(Vector3.Zero, Quaternion.Identity, transform.Scale, Vector3.Zero, transform.Rotation, transform.Position);

                        Vector3.TransformNormal(ref boundingBox.Minimum, ref matrix, out boundingBox.Minimum);
                        Vector3.TransformNormal(ref boundingBox.Maximum, ref matrix, out boundingBox.Maximum);

                        nodeIndex = node.ParentIndex;
                    }

                    collidableObstacle.BoundingBoxes.Add(boundingBox);
                }
            }
            else
            {
                // Use bounding box of the whole model
                collidableObstacle.BoundingBoxes.Add(modelComponent.Model.BoundingBox);
            }

            CollidableObstacles.Add(collidableObstacle);

            return(this);
        }
Пример #17
0
        /// <summary>
        /// Adds or forwards the received damage.
        /// </summary>
        /// <param name="_damage">Damage.</param>
        /// <param name="_damage_direction">Damage direction.</param>
        /// <param name="_attacker_position">Attacker position.</param>
        /// <param name="_attacker">Attacker.</param>
        /// <param name="_force">Force.</param>
        public virtual void AddDamage(float _damage, Vector3 _damage_direction, Vector3 _damage_position, Transform _attacker, float _force = 0)
        {
            // use RootEntity instead of m_RootEntity to make sure that the root will be up-to-date
            if (IsChildEntity && Status.UseDamageTransfer)
            {
                RootEntity.AddDamage(_damage * Status.DamageTransferMultiplier, _damage_direction, _damage_position, _attacker, _force);
            }
            else
            {
                Status.AddDamage(_damage * Status.DamageTransferMultiplier);

                if (OnAddDamage != null)
                {
                    OnAddDamage(_damage * Status.DamageTransferMultiplier, _damage_direction, _damage_position, _attacker, _force);
                }
            }

            //ApplyImpact( _damage_direction, _force );
        }
Пример #18
0
        private void AssertTwoRootEntitiesEquals(RootEntity entityA, RootEntity entityB)
        {
            Assert.AreEqual(entityA.IdCol, entityB.IdCol);

            Assert.AreEqual(entityA.CharNotNull, entityB.CharNotNull);
            Assert.AreEqual(entityA.CharNull, entityB.CharNull);
            Assert.AreEqual(entityA.DateNotNull, entityB.DateNotNull);
            Assert.AreEqual(entityA.DateNull, entityB.DateNull);
            Assert.AreEqual(entityA.DoubleNotNull, entityB.DoubleNotNull);
            Assert.AreEqual(entityA.DoubleNull, entityB.DoubleNull);
            Assert.AreEqual(entityA.FloatNotNull, entityB.FloatNotNull);
            Assert.AreEqual(entityA.FloatNull, entityB.FloatNull);
            Assert.AreEqual(entityA.IntNotNull, entityB.IntNotNull);
            Assert.AreEqual(entityA.IntNull, entityB.IntNull);
            Assert.AreEqual(entityA.LongNotNull, entityB.LongNotNull);
            Assert.AreEqual(entityA.LongNull, entityB.LongNull);
            Assert.AreEqual(entityA.TimestampNotNull, entityB.TimestampNotNull);
            Assert.AreEqual(entityA.TimestampNull, entityB.TimestampNull);
            Assert.AreEqual(entityA.VarcharNotNull, entityB.VarcharNotNull);
            Assert.AreEqual(entityA.VarcharNull, entityB.VarcharNull);
            Assert.AreEqual(entityA.LeafEntities.Count, entityB.LeafEntities.Count);

            IEnumerator <LeafEntity> iteratorA = entityA.LeafEntities.GetEnumerator();

            while (iteratorA.MoveNext())
            {
                LeafEntity leafEntityA = iteratorA.Current;
                bool       bFound      = false;
                foreach (LeafEntity leafEntityB in entityB.LeafEntities)
                {
                    if (leafEntityB.IdCol == leafEntityA.IdCol &&
                        leafEntityB.IndexNo == leafEntityA.IndexNo)
                    {
                        bFound = true;
                        AssertTwoLeafEntitiesTypeAEquals(leafEntityA, leafEntityB);
                    }
                }
                if (!bFound)
                {
                    Assert.Fail("Could not found matching leaf entity");
                }
            }
        }
Пример #19
0
        public void ShouldRemoveAssociateWithRequiredAssociateIfRequiredIsNotSet()
        {
            var targetRequired = new RequiredAssociate();
            var sourceRequired = new RequiredAssociate();
            var source         = new RootEntity();
            var target         = new RootEntity();

            using (var context = new TestDbContext())
            {
                context.RequiredAssociates.Add(targetRequired);
                context.RequiredAssociates.Add(sourceRequired);

                context.RootEntities.Add(source);
                source.RequiredAssociate = sourceRequired;

                context.RootEntities.Add(target);
                target.RequiredAssociate = targetRequired;
                target.Sources           = new List <RootEntity> {
                    source
                };

                context.SaveChanges();
            }

            target.Sources.Remove(source);

            int expectedSourceId         = source.Id;
            int expectedTargetId         = target.Id;
            int expectedTargetRequiredId = targetRequired.Id;

            using (var context = new TestDbContext())
            {
                context.UpdateGraph(target, map => map.AssociatedCollection(c => c.Sources).AssociatedEntity(c => c.RequiredAssociate));
                context.SaveChanges();

                Assert.IsNotNull(context.RequiredAssociates.FirstOrDefault(p => p.Id == expectedTargetRequiredId));
                Assert.IsNotNull(context.RootEntities.FirstOrDefault(p => p.Id == expectedSourceId));

                var targetReloaded = context.RootEntities.Include("Sources").FirstOrDefault(c => c.Id == expectedTargetId);
                Assert.IsNotNull(targetReloaded);
                Assert.AreEqual(0, targetReloaded.Sources.Count);
            }
        }
Пример #20
0
        public override void Render()
        {
            GL.ClearColor(Color.CornflowerBlue);
            GL.PointSize(5f);

            //GL.Viewport(0, 0, Width, Height);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            //GL.Enable(EnableCap.LineSmooth); // This is Optional
            //GL.Enable(EnableCap.RescaleNormal);

            base.Render();

            RootEntity.Render();

            GL.Flush();
        }
Пример #21
0
        public void PatchEmpty_PatchDataBase_WithEmptyDb_ShouldCreateForeignKeys_ShouldNotAbleToInconsistantData()
        {
            ITransaction transaction = CreateTransaction();

            int        id     = 38;
            RootEntity entity = CreateRootEntityWithoutNullValues(id);

            entity.Persist(transaction);

            var leafEntityA = CreateLeafEntityA(id, 1);

            leafEntityA.Persist(transaction);

            var leafEntityB = CreateLeafEntityA(id + 1, 1);

            Assert.Throws <PersistException>(() => leafEntityB.Persist(transaction));

            transaction.Commit();
            transaction.Close();
        }
Пример #22
0
        public void StatusUtility_SetStatus_WithMultiLevelHirachy_ShouldSetStatus()
        {
            var rootEntity  = new RootEntity();
            var leafEntityA = new LeafEntity();

            rootEntity.LeafEntities.Add(leafEntityA);
            var leafEntityB = new LeafEntity();

            rootEntity.LeafEntities.Add(leafEntityB);
            var leafEntityNotNull = new LeafEntity();

            rootEntity.LeafEntityNotNull = leafEntityNotNull;
            rootEntity.LeafEntityNull    = null;

            StatusManager.SetStatus(rootEntity, EntityStatus.Modified);

            Assert.AreEqual(rootEntity.Status, EntityStatus.Modified);
            Assert.AreEqual(leafEntityA.Status, EntityStatus.Modified);
            Assert.AreEqual(leafEntityB.Status, EntityStatus.Modified);
            Assert.AreEqual(leafEntityNotNull.Status, EntityStatus.Modified);
        }
Пример #23
0
        public void ShouldAddTwoAssociatesWithSharedRequiredAssociate()
        {
            var root = new RootEntity {
                RequiredAssociate = new RequiredAssociate(), Sources = new List <RootEntity>()
            };
            var requiredAssociate = new RequiredAssociate();
            var associateOne      = new RootEntity {
                RequiredAssociate = requiredAssociate
            };
            var associateTwo = new RootEntity {
                RequiredAssociate = requiredAssociate
            };

            using (var context = new TestDbContext())
            {
                context.RootEntities.Add(root);
                context.RootEntities.Add(associateOne);
                context.RootEntities.Add(associateTwo);
                context.RequiredAssociates.Add(requiredAssociate);
                context.SaveChanges();
            } // Simulate detach

            var expectedAssociateId = requiredAssociate.Id;

            root.Sources.Add(associateOne);
            root.Sources.Add(associateTwo);

            using (var context = new TestDbContext())
            {
                root = context.UpdateGraph(root, map => map.AssociatedCollection(r => r.Sources).AssociatedEntity(r => r.RequiredAssociate));
                context.SaveChanges();

                Assert.IsTrue(root.Sources.All(s => s.RequiredAssociate.Id == expectedAssociateId));

                var sourceIds       = root.Sources.Select(s => s.Id).ToArray();
                var sourcesReloaded = context.RootEntities.Where(r => sourceIds.Contains(r.Id)).ToList();
                Assert.IsTrue(sourcesReloaded.All(s => s.RequiredAssociate != null && s.RequiredAssociate.Id == expectedAssociateId));
            }
        }
Пример #24
0
        public void StatusUtility_GetImmidiateChildrenAndClear_WithMultiLevelHirachy_ShouldGetChildren()
        {
            var rootEntity  = new RootEntity();
            var leafEntityA = new LeafEntity();

            rootEntity.LeafEntities.Add(leafEntityA);
            var leafEntityB = new LeafEntity();

            rootEntity.LeafEntities.Add(leafEntityB);
            var leafEntityNotNull = new LeafEntity();

            rootEntity.LeafEntityNotNull = leafEntityNotNull;
            rootEntity.LeafEntityNull    = null;

            ICollection <IClientEntity> childern = StatusManager.GetImmidiateChildrenAndClear(rootEntity);

            Assert.IsTrue(childern.Contains(leafEntityA));
            Assert.IsTrue(childern.Contains(leafEntityB));
            Assert.IsTrue(childern.Contains(leafEntityNotNull));
            Assert.IsTrue(rootEntity.LeafEntities.Count == 0);
            Assert.IsNull(rootEntity.LeafEntityNotNull);
        }
Пример #25
0
        public void RootEntity_AddNewChild_StateShould()
        {
            // Arrange
            var root = new RootEntity();

            Assert.Equal(State.Unchanged, root.State);
            Assert.Null(root.ChildEntity);

            var newChild = new ChildEntity();

            Assert.Equal(State.Unchanged, newChild.State);

            newChild.Create();
            Assert.Equal(State.Added, newChild.State);

            // Act
            root.SetChildEntity(newChild);

            // Assert
            Assert.Equal(State.Modified, root.State);
            Assert.Equal(State.Added, root.ChildEntity.State);
        }
Пример #26
0
        public void ShouldAddAssociatedWithoutChangingRequiredAssociate()
        {
            var root = new RootEntity {
                RequiredAssociate = new RequiredAssociate(), Sources = new List <RootEntity>()
            };
            var requiredAssociate = new RequiredAssociate();
            var owned             = new RootEntity {
                RequiredAssociate = requiredAssociate
            };

            using (var context = new TestDbContext())
            {
                context.RootEntities.Add(root);
                context.RootEntities.Add(owned);
                context.RequiredAssociates.Add(requiredAssociate);
                context.SaveChanges();
            } // Simulate detach

            var expectedAssociateId = requiredAssociate.Id;

            root.Sources.Add(owned);

            using (var context = new TestDbContext())
            {
                root = context.UpdateGraph(root, map => map.AssociatedCollection(r => r.Sources).AssociatedEntity(r => r.RequiredAssociate));
                context.SaveChanges();

                var ownedAfterSave = root.Sources.FirstOrDefault();
                Assert.IsNotNull(ownedAfterSave);
                Assert.IsNotNull(ownedAfterSave.RequiredAssociate);
                Assert.AreEqual(expectedAssociateId, ownedAfterSave.RequiredAssociate.Id);

                var ownedReloaded = context.RootEntities.Single(r => r.Id == ownedAfterSave.Id);
                Assert.IsNotNull(ownedReloaded.RequiredAssociate);
                Assert.AreEqual(expectedAssociateId, ownedReloaded.RequiredAssociate.Id);
            }
        }
Пример #27
0
        static async Task <string?> ApplyTemplateAsync(
            EntityTemplate template,
            EntityTemplateFunctions functions,
            TemplateImportState state,
            SeqConnection connection,
            RootEntity apiRoot,
            bool merge)
        {
            if (!JsonTemplateEvaluator.TryEvaluate(template.Entity, functions.Exports, out var entity, out var error))
            {
                return(error);
            }

            var asObject = (IDictionary <string, object>)JsonTemplateObjectGraphConverter.Convert(entity);

            // O(Ntemplates) - easy target for optimization with some caching.
            var resourceGroupLink = template.ResourceGroup + "Resources";
            var link          = apiRoot.Links.Single(l => resourceGroupLink.Equals(l.Key, StringComparison.OrdinalIgnoreCase));
            var resourceGroup = await connection.Client.GetAsync <ResourceGroup>(apiRoot, link.Key);

            if (state.TryGetCreatedEntityId(template.Name, out var existingId) &&
                await CheckEntityExistenceAsync(connection, resourceGroup, existingId))
            {
                asObject["Id"] = existingId;
                await UpdateEntityAsync(connection, resourceGroup, asObject, existingId);

                Log.Information("Updated existing entity {EntityId} from {TemplateName}", existingId, template.Name);
            }
            else if (merge && !state.TryGetCreatedEntityId(template.Name, out _) &&
                     await TryFindMergeTargetAsync(connection, resourceGroup, asObject) is { } mergedId)
            {
                asObject["Id"] = mergedId;
                await UpdateEntityAsync(connection, resourceGroup, asObject, mergedId);

                state.AddOrUpdateCreatedEntityId(template.Name, mergedId);
                Log.Information("Merged and updated existing entity {EntityId} from {TemplateName}", existingId, template.Name);
            }
Пример #28
0
        public void RootEntity_AddExistingChildCollection_StateShould()
        {
            // Arrange
            var root = new RootEntity();

            Assert.Equal(State.Unchanged, root.State);

            var child = new ChildEntity();

            Assert.Equal(State.Unchanged, child.State);

            // Act
            root.AddChildCollection(child);
            Assert.Single(root.ChildCollection);
            Assert.Equal(State.Unchanged, root.ChildCollection.FirstOrDefault().State);

            root.ChildCollection.Add(new ChildEntity());
            Assert.Equal(2, root.ChildCollection.Count);

            // Assert
            Assert.Equal(State.Modified, root.State);
            Assert.Equal(State.Unchanged, root.ChildCollection[0].State);
            Assert.Equal(State.Unchanged, root.ChildCollection[1].State);
        }
Пример #29
0
        private RootEntity LoadRootEntityWithId(ITransaction transaction, int id)
        {
            RootEntity loadedEntity = null;

            IDbCommand cmd = transaction.CreateCommand();

            cmd.CommandText = "select * from root_entity where id_col = ?";

            IDbDataParameter parameter = cmd.CreateParameter();

            cmd.Parameters.Add(parameter);
            parameter.DbType = DbType.Int32;
            parameter.Value  = id;

            IDataReader rs = cmd.ExecuteReader();

            if (rs.Read())
            {
                loadedEntity = new RootEntity();
                loadedEntity.Retrieve(rs, transaction);
            }

            return(loadedEntity);
        }
Пример #30
0
 public override void CleanUp()
 {
     RootEntity.CleanUp();
 }
Пример #31
0
        public void Mapping_is_done_recursively()
        {
            var entity = new RootEntity
                {
                    String = "string 1",
                    Related = new RelatedEntity
                        {
                            Enum = SomeEnum.Value3
                        },
                    Children = new[]
                        {
                            new ChildEntity()
                                {
                                    Int = 1,
                                    GrandChildren = null,
                                },
                            new ChildEntity()
                                {
                                    Int = 2,
                                    GrandChildren = new List<GrandChildEntity>()
                                        {
                                            new GrandChildEntity
                                                {
                                                    Double = 1.23,
                                                    AnotherRelated = new RelatedEntity
                                                        {
                                                            Enum = SomeEnum.Value2
                                                        }
                                                },
                                            new GrandChildEntity
                                                {
                                                    Double = 2.34,
                                                    AnotherRelated = null
                                                }
                                        }
                                },
                        }
                };

            var rootDto = _mapper.Map<RootDTO>(entity);

            Assert.AreEqual("string 1", rootDto.String);
            Assert.IsNotNull(rootDto.Related);
            Assert.AreEqual(SomeOtherEnum.OtherValue3, rootDto.Related.Enum);
            Assert.AreEqual(2, rootDto.Children.Count());

            var firstChildDto = rootDto.Children.First();
            var secondChildDto = rootDto.Children.Last();
            
            Assert.AreEqual(1, firstChildDto.Int);
            Assert.IsNull(firstChildDto.GrandChildren);

            Assert.AreEqual(2, secondChildDto.Int);
            Assert.IsNotNull(secondChildDto.GrandChildren);
            Assert.AreEqual(2, secondChildDto.GrandChildren.Count());
            Assert.AreEqual(1.23, secondChildDto.GrandChildren.First().Double);
            Assert.IsNotNull(secondChildDto.GrandChildren.First().AnotherRelated);
            Assert.AreEqual(SomeOtherEnum.OtherValue2, secondChildDto.GrandChildren.First().AnotherRelated.Enum);
            Assert.IsNull(secondChildDto.GrandChildren.Last().AnotherRelated);
            Assert.AreEqual(2.34, secondChildDto.GrandChildren.Last().Double);
        }