Example #1
0
        private void SpawnPlayer(BulletFactory bulletFactory)
        {
            var spaceshipTexture = Content.Load <Texture2D>("playerShip1_blue");
            var spaceshipRegion  = new TextureRegion2D(spaceshipTexture);

            _player = _entityManager.AddEntity(new Spaceship(spaceshipRegion, bulletFactory));
        }
Example #2
0
        public void GenerateSeeds()
        {
            for (int i = 0; i < 2; i++)
            {
                Seed s = new Seed(CheckpointGenerator.RandomOffset(NamedPositions.ChickenCoopOutside, 300));
                EntityManager.AddEntity(s);
            }

            for (int i = 0; i < 5; i++)
            {
                Seed s = new Seed(CheckpointGenerator.RandomOffset(NamedPositions.Sandbox, 600));
                EntityManager.AddEntity(s);
            }

            for (int i = 0; i < 2; i++)
            {
                Seed s = new Seed(CheckpointGenerator.RandomOffset(NamedPositions.Lake, 100));
                EntityManager.AddEntity(s);
            }

            for (int i = 0; i < 7; i++)
            {
                Seed s = new Seed(CheckpointGenerator.RandomOffset(NamedPositions.Grass, 600));
                EntityManager.AddEntity(s);
            }

            // hardcoded number of seeds :|
            GameState.Instance.SetVar <int>("totalSeeds", 16);
        }
Example #3
0
        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            _sfxButtonPress     = Content.Load <SoundEffect>(ASSET_NAME_SFX_BUTTON_PRESS);
            _sfxHit             = Content.Load <SoundEffect>(ASSET_NAME_SFX_HIT);
            _sfxScoreReached    = Content.Load <SoundEffect>(ASSET_NAME_SFX_SCORE_REACHED);
            _spriteSheetTexture = Content.Load <Texture2D>(ASSET_NAME_SPRITESHEET);


            _fadeInAnimation = new Texture2D(GraphicsDevice, 1, 1);
            _fadeInAnimation.SetData(new Color[] { Color.White });


            _TRex           = new TRex(_spriteSheetTexture, new Vector2(Trexpos, TrexYpos - TRex.TrexHeiht), _sfxButtonPress);
            _TRex.DrewOrder = 10;


            _InputController = new ImputController(_TRex);

            _groundmanager = new GroundManager(_spriteSheetTexture, _entityManager, _TRex);

            _entityManager.AddEntity(_TRex);
            _entityManager.AddEntity(_groundmanager);

            _groundmanager.Initialize();
        }
Example #4
0
        public async Task SaveAdded()
        {
            await _emTask;

            var supplier = new Supplier();

            supplier.CompanyName = "Test-" + TestFns.RandomSuffix(5);
            var companyName = supplier.CompanyName;

            supplier.Location = new Location()
            {
                Region = "USA", Address = "123 Main Street", City = "San Diego", PostalCode = "12345"
            };
            _em1.AddEntity(supplier);

            var sr = await _em1.SaveChanges();

            Assert.IsTrue(sr.Entities.Count == 1);
            var ek = sr.Entities.First().EntityAspect.EntityKey;

            var _em2 = new EntityManager(_em1);
            var q1   = ek.ToQuery <Supplier>();
            var r1   = await q1.Execute(_em2);

            Assert.IsTrue(r1.Count() == 1);
            Assert.IsTrue(r1.First().CompanyName == companyName, "should have set the companyName");
            Assert.IsTrue(r1.First().Location.City == "San Diego");
            Assert.IsTrue(r1.First().Location.PostalCode == "12345");
        }
Example #5
0
 public Entity LoadPlayer(string fileId, int posX = -1, int posY = -1, int dir = -1)
 {
     player = LoadEntity(fileId);
     if (player != null)
     {
         player.Type = EntityType.Player;
         if (posX >= 0 && posY >= 0)
         {
             player.MapPosX = posX + 0.5f;
             player.MapPosY = posY + 0.5f;
         }
         else
         {
             player.MapPosX = map.StartX + 0.5f;
             player.MapPosY = map.StartY + 0.5f;
         }
         player.TrackWithCamera = true;
         player.MoveWithMouse   = true;
         player.TriggersEvents  = true;
         if (dir >= 0)
         {
             player.Direction = dir;
         }
         entityManager.AddEntity(player);
         OnPlayerLoaded(player);
     }
     return(player);
 }
Example #6
0
        protected override void LoadContent()
        {
            _random = new Random();

            _spriteBatch = new SpriteBatch(GraphicsDevice);

            Textures.textures["squere"] = Content.Load <Texture2D>("Textures/squere");
            Textures.textures["flag"]   = Content.Load <Texture2D>("Textures/flag");
            Textures.textures["empty"]  = Content.Load <Texture2D>("Textures/empty");
            Textures.textures["bomb"]   = Content.Load <Texture2D>("Textures/bomb");
            _layer       = Content.Load <Texture2D>("Textures/Layer");
            _buttonReset = Content.Load <Texture2D>("Textures/ResetButton");

            for (int i = 1; i <= 8; i++)
            {
                Textures.textures[$"{ i }"] = Content.Load <Texture2D>($"Textures/{ i }");
            }

            _layerSprite           = new Layer(new Sprite(_layer, 0, 0, LAYER_WIDTH, LAYER_HEIGHT), new Vector2(0, 0));
            _layerSprite.DrawOrder = 1;

            _counter           = new BombsCounter(Content.Load <SpriteFont>("Text/BombsCount"), new Vector2(50, 50), _bombs);
            _counter.DrawOrder = 3;

            _resetButton           = new Button(new Sprite(_buttonReset, 0, 0, RESET_BUTTON_WIDTH, RESET_BUTTON_HEIGHT), new Vector2(227, 46));
            _resetButton.DrawOrder = 2;

            InitGame();

            _entityManager.AddEntity(_layerSprite);
            _entityManager.AddEntity(_counter);
            _entityManager.AddEntity(_resetButton);
        }
Example #7
0
        public void AddEntity_ReturnsEntity_Twice()
        {
            EntityManager manager = new EntityManager();

            manager.AddEntity();
            Entity e = manager.AddEntity();

            Assert.AreEqual(1, e.Id);
        }
Example #8
0
        public void LoadContent(ContentManager content)
        {
            _entityManager = new EntityManager();

            _map               = FileReadWriter.ReadFromBinary <Map>(MapDirectory);
            _tileset           = content.Load <Texture2D>(_map.TextureMap.TileTexture);
            _textureBackground = content.Load <Texture2D>("sprites/backgrounds/background1");
            _song              = content.Load <Song>("music/AVoid");
            MediaPlayer.Play(_song);
            MediaPlayer.IsRepeating = true;

            KeyboardInput.AddKey(Microsoft.Xna.Framework.Input.Keys.Space);


            int curPlat = 0;

            for (int x = 0; x < _map.Width; x++)
            {
                for (int y = 0; y < _map.Height; y++)
                {
                    if (_map.Tiles[x, y].ID != 8 &&
                        _map.Tiles[x, y].ID != 10 &&
                        _map.Tiles[x, y].ID != 11 &&
                        _map.Tiles[x, y].ID != 12 &&
                        _map.Tiles[x, y].ID != 13 &&
                        _map.Tiles[x, y].ID != 17 &&
                        _map.Tiles[x, y].ID != 18 &&
                        _map.Tiles[x, y].ID != 19)
                    {
                        //content.Load<Texture2D>(@"sprites/objects/warpBall")
                        _entityManager.AddEntity(new EntityPlatform("platform" + curPlat++, null, new Vector2(x * (_map.TextureMap.TileWidth) * 2.0f, y * (_map.TextureMap.TileHeight * 2.0f)) - _position, new Vector2((_map.TextureMap.TileWidth * 2.0f), (_map.TextureMap.TileHeight * 2.0f)), true));
                    }
                }
            }


            //_oldPlayerPos = _entityManager.GetEntity("player").GetComponent<ComponentTransform>().WorldTransform.Translate;

            _entityManager.AddEntity(new EntityProjectile("player",
                                                          content.Load <Texture2D>(@"sprites/player/char1"),
                                                          new Vector2(400.0f, 240.0f),
                                                          new Vector2(32.0f, 64.0f), true));

            _oldPlayerPos = _entityManager.GetEntity("player").GetComponent <ComponentTransform>().WorldTransform.Translate;


            _entityManager.AddEntity(new EntityProjectile("warpBall",
                                                          content.Load <Texture2D>(@"sprites/objects/warpBall"),
                                                          new Vector2(400.0f, 240.0f),
                                                          new Vector2(32.0f, 32.0f), true));
            //_entityManager.GetEntity("warpBall").GetComponent<ComponentTransform>().SetParent(_entityManager.GetEntity("player").GetComponent<ComponentTransform>());
            _entityManager.GetEntity("warpBall").GetComponent <ComponentTransform>().Scale = 0.6f;
            _entityManager.GetEntity("warpBall").GetComponent <ComponentCollision>().SetSize(32.0f * 0.6f, 32.0f * 0.6f);
            _entityManager.GetEntity("warpBall").GetComponent <ComponentPhysics>().DragX = 0.9999f;
        }
Example #9
0
        public void AddEntity_ReturnsEntity_Random([Random(1, 1000, 5)] int times)
        {
            EntityManager manager = new EntityManager();

            for (int i = 0; i < times - 1; i++)
            {
                manager.AddEntity();
            }

            Entity e = manager.AddEntity();

            Assert.AreEqual(times - 1, e.Id);
        }
Example #10
0
        public void LoadContent(ContentManager content)
        {
            MouseManager.CurrentCursor = MouseManager.Cursor.CROSSHAIR;
            _song = content.Load <Song>(@"music/AVoid");
            MediaPlayer.Play(_song);
            MediaPlayer.IsRepeating = true;


            _entityManager.AddEntity(new EntityProjectile("testEntity", content.Load <Texture2D>(@"sprites/player/Character"), new Vector2(100.0f, 100.0f), new Vector2(32.0f, 32.0f), true));
            _entityManager.AddEntity(new EntityPlatform("platform", content.Load <Texture2D>(@"sprites/tiles/texture1"), new Vector2(75.0f, 200.0f), new Vector2(225.0f, 96.0f), true));


            _entityManager.LoadContent(content);
        }
Example #11
0
        private void SpawnPlayers()
        {
            PlayerOne = entityManager.AddEntity(new Player());
            PlayerTwo = entityManager.AddEntity(new Player());

            Vector2 playerOnePosition = new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X + 50, GraphicsDevice.Viewport.TitleSafeArea.Y + GraphicsDevice.Viewport.TitleSafeArea.Height / 2);
            Vector2 playerTwoPosition = new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X + 200, GraphicsDevice.Viewport.TitleSafeArea.Y + GraphicsDevice.Viewport.TitleSafeArea.Height / 2);

            PlayerOne.Initialize(Content.Load <Texture2D>("player1"), playerOnePosition, new PlayerControls(Keys.Right, Keys.Left, Keys.Up, Keys.Down));
            PlayerTwo.Initialize(Content.Load <Texture2D>("player2"), playerTwoPosition, new PlayerControls(Keys.D, Keys.A, Keys.W, Keys.S));

            collisionComponent.Insert(PlayerOne);
            collisionComponent.Insert(PlayerTwo);
        }
        public void Initialize()
        {
            _grounds.Clear();

            foreach (GroundEntity gt in _entityManager.GetEntitiesOfType <GroundEntity>())
            {
                _entityManager.RemoveEntity(gt);
            }

            GroundEntity ground = new GroundEntity(_texture, new Vector2(GROUND_POS_X, GROUND_POS_Y));

            _grounds.Add(ground);

            _entityManager.AddEntity(ground);
        }
Example #13
0
        public static void Spawn(string name, int x, int y)
        {
            switch (name)
            {
            case "MARIA":
                GameObject maria = Factory.CreateMaria();
                maria.Position = new Vector2(x * TileMap.TileWidth, y * TileMap.TileHeight);
                EntityManager.AddEntity(maria);
                break;

            case "WATER":
                GameObject water = Factory.CreateWater();
                water.Position = new Vector2(x * TileMap.TileWidth, y * TileMap.TileHeight);
                EntityManager.AddEntity(water);
                break;

            case "PARTY":
                GameObject memberOne = Factory.CreatePartyMember();
                memberOne.Position = new Vector2(x * TileMap.TileWidth, y * TileMap.TileHeight);
                EntityManager.AddEntity(memberOne);

                GameObject memberTwo = Factory.CreatePartyMember();
                memberTwo.Position = new Vector2(x * TileMap.TileWidth, y * TileMap.TileHeight);
                EntityManager.AddEntity(memberTwo);

                GameObject memberThree = Factory.CreatePartyMember();
                memberThree.Position = new Vector2(x * TileMap.TileWidth, y * TileMap.TileHeight);
                EntityManager.AddEntity(memberThree);

                memberOne.Send("WAYPOINT_FOLLOW", VariableProvider.CurrentPlayer);
                memberTwo.Send("WAYPOINT_FOLLOW", memberOne);
                memberThree.Send("WAYPOINT_FOLLOW", memberTwo);
                break;
            }
        }
Example #14
0
        public async Task HasChangesChangedAfterSave()
        {
            await _emTask;

            var hccArgs = new List <EntityManagerHasChangesChangedEventArgs>();

            _em1.HasChangesChanged += (s, e) => {
                hccArgs.Add(e);
            };

            var emp = new Employee()
            {
                FirstName = "Test_Fn", LastName = "Test_Ln"
            };

            _em1.AddEntity(emp);
            Assert.IsTrue(hccArgs.Count == 1);
            Assert.IsTrue(hccArgs.Last().HasChanges == true);
            Assert.IsTrue(_em1.HasChanges());
            var sr = await _em1.SaveChanges();

            Assert.IsTrue(sr.Entities.Count == 1);
            Assert.IsTrue(hccArgs.Count == 2);
            Assert.IsTrue(hccArgs.Last().HasChanges == false);
            Assert.IsTrue(_em1.HasChanges() == false);
        }
Example #15
0
        public override void OnInitialize(EntityManager manager)
        {
            clickAreaThis = AddClickMouseArea(FRectangle.CreateByCenter(0, 0, DIAMETER, DIAMETER), OnClick, OnDown, OnUp);

            var cfg = new ParticleEmitterConfig.ParticleEmitterConfigBuilder
            {
                // red fire
                TextureIndex         = 12,
                SpawnRate            = 20,
                ParticleLifetimeMin  = 1.0f,
                ParticleLifetimeMax  = 2.5f,
                ParticleVelocityMin  = 24f,
                ParticleVelocityMax  = 32f,
                ParticleSizeInitial  = 64,
                ParticleSizeFinalMin = 32,
                ParticleSizeFinalMax = 48,
                ParticleAlphaInitial = 1f,
                ParticleAlphaFinal   = 0f,
                ColorInitial         = Color.DarkOrange,
                ColorFinal           = Color.DarkRed,
            }.Build(Textures.TexParticle);

            emitter = new PointCPUParticleEmitter(Owner, Position, cfg, GDConstants.ORDER_MAP_NODEPARTICLES);

            manager.AddEntity(emitter);
        }
        public Player(string name, Camera camera, EntityManager entityManager) : base(name)
        {
            callUpdate       = true;
            camera.transform = transform;
            attachedCamera   = camera;
            attachedCamera.deltaPosition.Z = -0.4f;

            AddComponent(new ComponentGeometry("Arm Only.obj"));
            AddComponent(new ComponentMaterial("arm.png"));
            AddComponent(new ComponentCollider_Sphere(0.46f, transform));
            AddComponent(new ComponentVelocity(0, 0, 0));
            AddComponent(new ComponentSound(new string[] { "Audio/death.wav" }));
            transform.scale      = new Vector3(2);
            transform.position.Y = 1.2f;

            // set up first weapon
            weapon[0] = new BasicWeapon("Weapon 1", damage: 30);
            weapon[0].AddComponent(new ComponentGeometry("Weapon1.obj"));
            weapon[0].AddComponent(new ComponentMaterial("Weapon1.png"));
            weapon[0].AddComponent(new ComponentSound(new string[] { "Audio/weapon.wav" }));
            entityManager.AddEntity(weapon[0]);

            ResetEvent  = null;
            ResetEvent += ResetPlayer;
        }
Example #17
0
        internal override void Update(int x, int y)
        {
            if (cooldown == null)
            {
                cooldown = new CooldownTimer(30);
            }

            BoundedFloat buffer = new BoundedFloat(0, 0, cost);

            CachePowerLevels();

            if (powerinL + powerinR + powerinD + powerinU >= buffer.max)
            {
                BoundedFloat.MoveVals(ref powerinL, ref buffer, powerinL);
                BoundedFloat.MoveVals(ref powerinR, ref buffer, powerinR);
                BoundedFloat.MoveVals(ref powerinD, ref buffer, powerinD);
                BoundedFloat.MoveVals(ref powerinU, ref buffer, powerinU);
            }

            EmptyInputs();

            if (buffer.IsFull())
            {
                state = true;

                var pos      = new Vector2(x - range, y - range);
                var size     = new Vector2(2 * range, 2 * range);
                var entities = EntityManager.GetEntitiesAt(pos, size, e => !(e is AutoDart || e is Player || e.data.invulnerable));

                if (cooldown.Ready())
                {
                    if (entities.Length > 0)
                    {
                        cooldown.Reset();

                        var e      = entities[MathUtil.RandInt(Program.Rand, 0, entities.Length - 1)];
                        var darvel = e.data.pos - new Vector2(x, y);
                        darvel = darvel.Normalize();
                        var dartpos = new Vector2(x, y);
                        dartpos += 1.5f * darvel;
                        darvel  /= 10;
                        var ad = new AutoDart(dartpos, darvel);
                        if (!ad.IsCollidingWithTerrain())
                        {
                            EntityManager.AddEntity(ad);
                        }
                    }
                    else
                    {
                        cooldown.SetTime(-100);
                    }
                }
            }
            else
            {
                state = false;
            }

            Terrain.TileAt(x, y).enumId = state ? TileID.AutoShooterOn : TileID.AutoShooterOff;
        }
        public void Update(double delta_time)
        {
            var entities = entity_manager.Entities;
            var n        = entities.Length;

            foreach (var chunk_loader_node in chunk_loader_nodes)
            {
                var chunk_loader_position = VectorToPoint(chunk_loader_node.Base.Position);

                for (var i = 0; i < n; i++)
                {
                    var entity = entities[i];

                    if (null == entity)
                    {
                        continue;
                    }

                    if (!entity.Has <BaseComponent>())
                    {
                        entities[i] = null;
                        continue;
                    }

                    var entity_position = VectorToPoint(entity.Get <BaseComponent>().Position);
                    foreach (var chunk in Chunks(chunk_loader_position))
                    {
                        if (chunk == entity_position)
                        {
                            entities[i] = null;
                        }
                    }
                }
            }

            for (var i = 0; i < n; i++)
            {
                var entity = entities[i];

                if (null == entity)
                {
                    continue;
                }

                entity_manager.RemoveEntity(entity);

                var thread = new Thread(() => { Save(VectorToPoint(entity.Get <BaseComponent>().Position), entity); });
                thread.IsBackground = true;
                thread.Start();
            }

            lock (loader_lock)
            {
                foreach (var loader_entity in loader_entities)
                {
                    entity_manager.AddEntity(loader_entity);
                }
                loader_entities.Clear();
            }
        }
    void Start()
    {
        Bandit testNPC = new Bandit();

        EntityManager.AddEntity(testNPC);
        EntityManager.LoadChunk(new Vec2i(0, 0));
    }
Example #20
0
        private TwoCusts CreateParentAndChildren(EntityManager em)
        {
            var cust1 = new Customer();

            cust1.CompanyName = "Test1_" + TestFns.RandomSuffix(8);
            cust1.City        = "Oakland";
            cust1.RowVersion  = 13;
            cust1.Fax         = "510 999-9999";
            em.AddEntity(cust1);
            var cust2 = em.CreateEntity <Customer>();

            cust2.CompanyName = "Test2_" + TestFns.RandomSuffix(8);
            cust2.City        = "Emeryville";
            cust2.RowVersion  = 1;
            cust2.Fax         = "510 888-8888";
            var order1 = new Order();

            order1.OrderDate = DateTime.Today;
            var order2 = em.CreateEntity <Order>();

            order1.OrderDate = DateTime.Today;
            cust1.Orders.Add(order1);
            cust1.Orders.Add(order2);
            Assert.IsTrue(cust1.Orders.Count == 2);
            Assert.IsTrue(cust2.Orders.Count == 0);
            return(new TwoCusts()
            {
                Cust1 = cust1, Cust2 = cust2
            });
        }
Example #21
0
        public void GetComponent_WhenNothing_ReturnsNull()
        {
            EntityManager manager = new EntityManager();
            Entity        e       = manager.AddEntity();

            Assert.IsNull(ComponentManager <PositionComponent> .Instance.GetComponent(e));
        }
        private void CreateEntityButton_Click(object sender, RoutedEventArgs e)
        {
            // Sanity Check
            if (EntityNameTextBox.Text == null || EntityNameTextBox.Text.Trim() == "")
            {
                MessageBox.Show("Input Name!");
                return;
            }
            else if (EntityOwnerTextBox.Text == null || EntityNameTextBox.Text.Trim() == "")
            {
                MessageBox.Show("Input Owner!");
                return;
            }
            else if (EntityDescTextBox.Text == null || EntityNameTextBox.Text.Trim() == "")
            {
                MessageBox.Show("Input Description!");
                return;
            }

            // Get the customer and create the entity and add it
            Customer customer = CustomerManager.GetCustomer(EntityOwnerTextBox.Text);

            Entity entity = new Entity
            {
                EntityDescription = EntityDescTextBox.Text,
                EntityName        = EntityNameTextBox.Text,
                EntityOwner       = customer
            };

            EntityManager.AddEntity(entity);
        }
Example #23
0
        private Product CreateProduct(EntityManager em)
        {
            var product = new Product();

            em.AddEntity(product);
            product.ProductName = "Test.NET_" + TestFns.RandomSuffix(7);
            return(product);
        }
Example #24
0
        //test("save/mods with EntityErrorsException", function () {
        //    if (testFns.DEBUG_ODATA) {
        //        ok(true, "Skipped test - OData does not support server interception or alt resources");
        //        return;
        //    };

        //    if (testFns.DEBUG_MONGO) {
        //        ok(true, "Skipped test - Mongo does not YET support server side validation");
        //        return;
        //    };


        //    var em = newEm();
        //    var zzz = createParentAndChildren(em);
        //    var cust1 = zzz.cust1;

        //    stop();
        //    em.saveChanges().then(function (sr) {
        //        zzz.cust1.setProperty("contactName", "foo");
        //        zzz.cust2.setProperty("contactName", "foo");
        //        zzz.order1.setProperty("freight", 888.11);
        //        zzz.order2.setProperty("freight", 888.11);
        //        ok(zzz.cust1.entityAspect.entityState.isModified(), "cust1 should be modified");
        //        ok(zzz.order1.entityAspect.entityState.isModified(), "order1 should be modified");
        //        var so = new SaveOptions({ resourceName: "SaveWithEntityErrorsException", tag: "entityErrorsException" });
        //        return em.saveChanges(null, so);
        //    }).then(function(sr2) {
        //        ok(false, "should not get here");
        //    }).fail(function (e) {
        //        ok(e.entityErrors, "should have server errors");
        //        ok(e.entityErrors.length === 2, "2 order entities should have failed");
        //        ok(zzz.order1.entityAspect.getValidationErrors().length === 1);
        //        var order2Errs = zzz.order2.entityAspect.getValidationErrors();
        //        ok(order2Errs.length === 1, "should be 1 error for order2");
        //        ok(order2Errs[0].propertyName === "orderID", "errant property should have been 'orderID'");
        //        // now save it properly
        //        return em.saveChanges();
        //    }).then(function (sr) {
        //        ok(sr.entities.length === 4, "should have saved ok");
        //    }).fail(testFns.handleFail).fin(start);

        //});

        //test("save with client side validation error", function () {

        //    var em = newEm();
        //    var zzz = createParentAndChildren(em);
        //    var cust1 = zzz.cust1;
        //    cust1.setProperty("companyName", null);
        //    stop();
        //    em.saveChanges().then(function (sr) {
        //        ok(false, "should not get here");
        //    }).fail(function (e) {
        //        ok(e.entityErrors, "should be a  entityError");
        //        ok(e.entityErrors.length === 1, "should be only one error");
        //        ok(!e.entityErrors[0].isServerError, "should NOT be a server error");
        //        var errors = cust1.entityAspect.getValidationErrors();
        //        ok(errors[0].errorMessage === errors[0].errorMessage, "error message should appear on the cust");

        //    }).fin(start);
        //});

        //test("save with server side entity level validation error", function () {
        //    if (testFns.DEBUG_ODATA) {
        //        ok(true, "Skipped test - OData does not support server interception or alt resources");
        //        return;
        //    };

        //    if (testFns.DEBUG_MONGO) {
        //        ok(true, "Skipped test - Mongo does not YET support server side validation");
        //        return;
        //    };

        //    var em = newEm();
        //    var zzz = createParentAndChildren(em);
        //    var cust1 = zzz.cust1;
        //    cust1.setProperty("companyName", "error");
        //    stop();
        //    em.saveChanges().then(function(sr) {
        //        ok(false, "should not get here");
        //    }).fail(function (e) {
        //        ok(e.entityErrors, "should be a server error");
        //        ok(e.entityErrors.length === 1, "should be only one server error");
        //        var errors = cust1.entityAspect.getValidationErrors();
        //        ok(errors[0].errorMessage === e.entityErrors[0].errorMessage, "error message should appear on the cust");
        //    }).fin(start);
        //});

        //test("save with server side entity level validation error + repeat", function () {
        //    if (testFns.DEBUG_ODATA) {
        //        ok(true, "Skipped test - OData does not support server interception or alt resources");
        //        return;
        //    };

        //    if (testFns.DEBUG_MONGO) {
        //        ok(true, "Skipped test - Mongo does not YET support server side validation");
        //        return;
        //    };

        //    var em = newEm();
        //    var zzz = createParentAndChildren(em);
        //    var cust1 = zzz.cust1;
        //    cust1.setProperty("companyName", "error");
        //    stop();
        //    em.saveChanges().then(function (sr) {
        //        ok(false, "should not get here");
        //    }).fail(function (e) {
        //        ok(e.entityErrors, "should be a server error");
        //        ok(e.entityErrors.length === 1, "should be only one server error");
        //        var errors = cust1.entityAspect.getValidationErrors();
        //        ok(errors.length === 1, "should only be 1 error");
        //        ok(errors[0].errorMessage === e.entityErrors[0].errorMessage, "error message should appear on the cust");
        //        return em.saveChanges();
        //    }).fail(function(e2) {
        //        ok(e2.entityErrors, "should be a server error");
        //        ok(e2.entityErrors.length === 1, "should be only one server error");
        //       var errors = cust1.entityAspect.getValidationErrors();
        //       ok(errors.length === 1, "should only be 1 error");
        //       ok(errors[0].errorMessage === e2.entityErrors[0].errorMessage, "error message should appear on the cust");
        //    }).fin(start);
        //});

        //test("add UserRole", function () {
        //    if (testFns.DEBUG_MONGO) {
        //        ok(true, "TODO for Mongo - needs to be written specifically for Mongo - should succeed in Mongo");
        //        return;
        //    }

        //    var em = newEm();
        //    var roleId;
        //    var userId = 6;
        //    var p2 = breeze.Predicate.create("userId", "ne", userId);
        //    var p1 = breeze.Predicate.create("userRoles", "all", p2);

        //    var q = new EntityQuery("Roles").where(p1).take(1);
        //    stop();
        //    q.using(em).execute().then(function (data) {
        //        ok(data.results.length === 1, "should be one result");
        //        var role = data.results[0];
        //        roleId = role.getProperty("id");

        //        var newUserRole = em.createEntity('UserRole', {
        //            userId: userId,
        //            roleId: roleId
        //        });

        //        return em.saveChanges();
        //    }).then(function (sr) {
        //        ok(true, "save succeeded");
        //        var resultRole = sr.entities[0];
        //        var roleId2 = resultRole.getProperty("roleId");
        //        ok(roleId2 === roleId, "roleIds match");
        //        var userId2 = resultRole.getProperty("userId");
        //        ok(userId2 === userId, "userIds match");

        //        // delete entity
        //        resultRole.entityAspect.setDeleted();
        //        return em.saveChanges();
        //    }).then(function (sr) {
        //        ok(true, "delete succeeded");
        //    }).fail(function (e) {
        //        ok(false, "error on save: " + e.message);
        //    }).fail(testFns.handleFail).fin(start);

        //});

        private Order CreateOrder(EntityManager em)
        {
            var order = new Order();

            em.AddEntity(order);
            order.ShipName = "Test.NET_" + TestFns.RandomSuffix(7);
            return(order);
        }
Example #25
0
        public void RemoveEntity_ReturnsFalse_WhenNull()
        {
            EntityManager manager = new EntityManager();

            manager.AddEntity();

            Assert.IsFalse(manager.DestroyEntity(null));
        }
Example #26
0
 private void SpawnCoin()
 {
     for (int i = 0; i < COINS_TO_SPAWN; i++)
     {
         CoinEntity wall = new CoinEntity(_texture, new Vector2(COIN_POS_X + i * COINS_DISTANCE, COIN_POS_Y), _ball);
         _entityManager.AddEntity(wall);
     }
 }
Example #27
0
 private void AddIfNotColliding(Entity e)
 {
     if (e.IsCollidingWithTerrain())
     {
         return;
     }
     EntityManager.AddEntity(e);
 }
Example #28
0
 private void SpawnWall(int height)
 {
     for (int i = 0; i < height; i++)
     {
         WallEntity wall = new WallEntity(_texture, new Vector2(WALL_POS_X, WALL_POS_Y - i * WALL_HEIGHT), _ball);
         _entityManager.AddEntity(wall);
     }
 }
Example #29
0
        public Particle(EntityID model, Vector2 pos) : base(model, pos)
        {
            Vector2 size = Assets.Models.GetModel(model).size;

            data         = new ParticleData();
            data.pos.val = pos;
            EntityManager.AddEntity(this);
        }
Example #30
0
        public void RemoveEntity_ReturnsTrue_WhenValid()
        {
            EntityManager manager = new EntityManager();
            Entity        e       = manager.AddEntity();

            Assert.AreEqual(0, e.Id);

            Assert.IsTrue(manager.DestroyEntity(e));
        }
        public async Task CreatingEntities()
        {
            var manager = new EntityManager(_serviceName);

            // Metadata must be fetched before CreateEntity() can be called
            await manager.FetchMetadata();

            //Snippet1
            var newCustomer = new Customer(); // rarely done in Breeze

            //Snippet2
            // Order uses an auto-generated key value
            var order = manager.CreateEntity<Order>();

            //Snippet3
            // If the key is not auto generated, it must be initialized by CreateEntity()
            var alpha = manager.CreateEntity<Customer>(new { CustomerID = Guid.NewGuid(), CompanyName = "Alpha" });

            //Snippet4
            // Unattached new customer so you can keep configuring it and add/attach it later
            // Key value initializer not required because new entity is not attached to entity manager
            var beta = manager.CreateEntity<Customer>(new { CompanyName = "Beta" }, EntityState.Detached);

            // Attached customer, as if retrieved from the database
            // Note that the key must be initialized when new entity will be in an attached state
            var gamma = manager.CreateEntity<Customer>(new { CustomerID = Guid.NewGuid(), CompanyName = "Gamma" }, EntityState.Unchanged);

            //Snippet5
            // Only need to do this once
            var metadataStore = manager.MetadataStore;                           // The model metadata known to this EntityManager instance
            var customerType = metadataStore.GetEntityType(typeof(Customer));    // Metadata about the Customer type

            // Do this for each customer to be created
            var acme = customerType.CreateEntity() as Customer;     // Returns Customer as IEntity
            acme.CompanyName = "Acme";                              // CompanyName is a required field
            acme.CustomerID = Guid.NewGuid();                       // Must set the key field before attaching to entity manager
            manager.AddEntity(acme);                                // Attach the entity as a new entity; it's EntityState is "Added"
        }
Example #32
0
 private Product CreateProduct(EntityManager em) {
   var product = new Product();
   em.AddEntity(product);
   product.ProductName = "Test.NET_" + TestFns.RandomSuffix(7);
   // only needed because of NH bug where we made 'rowVersion' nullable on the client.
   product.RowVersion = 0;
   return product;
 }
        public async Task USCustomerMustHaveValidZipCode()
        {
            var manager = new EntityManager(_serviceName); // new empty EntityManager
            await manager.FetchMetadata(); // required before creating a new entity

            var customerType = manager.MetadataStore.GetEntityType(typeof(Customer)); //get the Customer type

            try
            {
                // add US zip code validator to the entity (not to a property)
                customerType.Validators.Add(new ZipCodeValidator());

                var customer = new Customer { CustomerID = Guid.NewGuid(), CompanyName = "Boogaloo Board Games" };
                customer.Country = "USA";
                customer.PostalCode = "N2L 3G1"; // a Canadian postal code
                manager.AddEntity(customer);
                // force validation of  customer
                var errors = customer.EntityAspect.Validate();

                Assert.IsTrue(errors.Any(), String.Format("should have 1 error: {0}", errors.First().Message));

                customer.Country = "Canada";

                errors = customer.EntityAspect.Validate();

                Assert.IsFalse(errors.Any(), String.Format("should have no errors"));
            }
            finally
            {
                Assert.IsTrue(customerType.Validators.Remove(new ZipCodeValidator()));
            }
        }
Example #34
0
 private TwoCusts CreateParentAndChildren(EntityManager em) {
   var cust1 = new Customer();
   cust1.CompanyName = "Test1_" + TestFns.RandomSuffix(8);
   cust1.City = "Oakland";
   cust1.RowVersion = 13;
   cust1.Fax = "510 999-9999";
   em.AddEntity(cust1);
   var cust2 = em.CreateEntity<Customer>();
   cust2.CompanyName = "Test2_" + TestFns.RandomSuffix(8);
   cust2.City = "Emeryville";
   cust2.RowVersion = 1;
   cust2.Fax = "510 888-8888";
   var order1 = new Order();
   order1.OrderDate = DateTime.Today;
   var order2 = em.CreateEntity<Order>();
   order1.OrderDate = DateTime.Today;
   cust1.Orders.Add(order1);
   cust1.Orders.Add(order2);
   Assert.IsTrue(cust1.Orders.Count == 2);
   Assert.IsTrue(cust2.Orders.Count == 0);
   return new TwoCusts() { Cust1 = cust1, Cust2 = cust2 };
 }
Example #35
0
 private OrderDetail CreateOrderDetail(EntityManager em, Order order, Product product) {
   var od = new OrderDetail();
   var orderID = order.OrderID;
   var productID = product.ProductID;
   od.ProductID = productID;
   od.OrderID = orderID;
   od.Quantity = 1;
   od.UnitPrice = 3.14m;
   em.AddEntity(od);
   return od;
 }
Example #36
0
 private Product CreateProduct(EntityManager em) {
   var product = new Product();
   em.AddEntity(product);
   product.ProductName = "Test.NET_" + TestFns.RandomSuffix(7);
   return product;
 }
Example #37
0
    //test("save/mods with EntityErrorsException", function () {
    //    if (testFns.DEBUG_ODATA) {
    //        ok(true, "Skipped test - OData does not support server interception or alt resources");
    //        return;
    //    };

    //    if (testFns.DEBUG_MONGO) {
    //        ok(true, "Skipped test - Mongo does not YET support server side validation");
    //        return;
    //    };


    //    var em = newEm();
    //    var zzz = createParentAndChildren(em);
    //    var cust1 = zzz.cust1;
        
    //    stop();
    //    em.saveChanges().then(function (sr) {
    //        zzz.cust1.setProperty("contactName", "foo");
    //        zzz.cust2.setProperty("contactName", "foo");
    //        zzz.order1.setProperty("freight", 888.11);
    //        zzz.order2.setProperty("freight", 888.11);
    //        ok(zzz.cust1.entityAspect.entityState.isModified(), "cust1 should be modified");
    //        ok(zzz.order1.entityAspect.entityState.isModified(), "order1 should be modified");
    //        var so = new SaveOptions({ resourceName: "SaveWithEntityErrorsException", tag: "entityErrorsException" });
    //        return em.saveChanges(null, so);
    //    }).then(function(sr2) {
    //        ok(false, "should not get here");
    //    }).fail(function (e) {
    //        ok(e.entityErrors, "should have server errors");
    //        ok(e.entityErrors.length === 2, "2 order entities should have failed");
    //        ok(zzz.order1.entityAspect.getValidationErrors().length === 1);
    //        var order2Errs = zzz.order2.entityAspect.getValidationErrors();
    //        ok(order2Errs.length === 1, "should be 1 error for order2");
    //        ok(order2Errs[0].propertyName === "orderID", "errant property should have been 'orderID'");
    //        // now save it properly
    //        return em.saveChanges();
    //    }).then(function (sr) {
    //        ok(sr.entities.length === 4, "should have saved ok");
    //    }).fail(testFns.handleFail).fin(start);

    //});

    //test("save with client side validation error", function () {

    //    var em = newEm();
    //    var zzz = createParentAndChildren(em);
    //    var cust1 = zzz.cust1;
    //    cust1.setProperty("companyName", null);
    //    stop();
    //    em.saveChanges().then(function (sr) {
    //        ok(false, "should not get here");
    //    }).fail(function (e) {
    //        ok(e.entityErrors, "should be a  entityError");
    //        ok(e.entityErrors.length === 1, "should be only one error");
    //        ok(!e.entityErrors[0].isServerError, "should NOT be a server error");
    //        var errors = cust1.entityAspect.getValidationErrors();
    //        ok(errors[0].errorMessage === errors[0].errorMessage, "error message should appear on the cust");

    //    }).fin(start);
    //});

    //test("save with server side entity level validation error", function () {
    //    if (testFns.DEBUG_ODATA) {
    //        ok(true, "Skipped test - OData does not support server interception or alt resources");
    //        return;
    //    };

    //    if (testFns.DEBUG_MONGO) {
    //        ok(true, "Skipped test - Mongo does not YET support server side validation");
    //        return;
    //    };

    //    var em = newEm();
    //    var zzz = createParentAndChildren(em);
    //    var cust1 = zzz.cust1;
    //    cust1.setProperty("companyName", "error");
    //    stop();
    //    em.saveChanges().then(function(sr) {
    //        ok(false, "should not get here");
    //    }).fail(function (e) {
    //        ok(e.entityErrors, "should be a server error");
    //        ok(e.entityErrors.length === 1, "should be only one server error");
    //        var errors = cust1.entityAspect.getValidationErrors();
    //        ok(errors[0].errorMessage === e.entityErrors[0].errorMessage, "error message should appear on the cust");
    //    }).fin(start);
    //});

    //test("save with server side entity level validation error + repeat", function () {
    //    if (testFns.DEBUG_ODATA) {
    //        ok(true, "Skipped test - OData does not support server interception or alt resources");
    //        return;
    //    };

    //    if (testFns.DEBUG_MONGO) {
    //        ok(true, "Skipped test - Mongo does not YET support server side validation");
    //        return;
    //    };

    //    var em = newEm();
    //    var zzz = createParentAndChildren(em);
    //    var cust1 = zzz.cust1;
    //    cust1.setProperty("companyName", "error");
    //    stop();
    //    em.saveChanges().then(function (sr) {
    //        ok(false, "should not get here");
    //    }).fail(function (e) {
    //        ok(e.entityErrors, "should be a server error");
    //        ok(e.entityErrors.length === 1, "should be only one server error");
    //        var errors = cust1.entityAspect.getValidationErrors();
    //        ok(errors.length === 1, "should only be 1 error");
    //        ok(errors[0].errorMessage === e.entityErrors[0].errorMessage, "error message should appear on the cust");
    //        return em.saveChanges();
    //    }).fail(function(e2) {
    //        ok(e2.entityErrors, "should be a server error");
    //        ok(e2.entityErrors.length === 1, "should be only one server error");
    //       var errors = cust1.entityAspect.getValidationErrors();
    //       ok(errors.length === 1, "should only be 1 error");
    //       ok(errors[0].errorMessage === e2.entityErrors[0].errorMessage, "error message should appear on the cust");
    //    }).fin(start);
    //});
 
    //test("add UserRole", function () {
    //    if (testFns.DEBUG_MONGO) {
    //        ok(true, "TODO for Mongo - needs to be written specifically for Mongo - should succeed in Mongo");
    //        return;
    //    }

    //    var em = newEm();
    //    var roleId;
    //    var userId = 6;
    //    var p2 = breeze.Predicate.create("userId", "ne", userId);
    //    var p1 = breeze.Predicate.create("userRoles", "all", p2);

    //    var q = new EntityQuery("Roles").where(p1).take(1);
    //    stop();
    //    q.using(em).execute().then(function (data) {
    //        ok(data.results.length === 1, "should be one result");
    //        var role = data.results[0];
    //        roleId = role.getProperty("id");

    //        var newUserRole = em.createEntity('UserRole', {
    //            userId: userId,
    //            roleId: roleId
    //        });

    //        return em.saveChanges();
    //    }).then(function (sr) {
    //        ok(true, "save succeeded");
    //        var resultRole = sr.entities[0];
    //        var roleId2 = resultRole.getProperty("roleId");
    //        ok(roleId2 === roleId, "roleIds match");
    //        var userId2 = resultRole.getProperty("userId");
    //        ok(userId2 === userId, "userIds match");
            
    //        // delete entity
    //        resultRole.entityAspect.setDeleted();
    //        return em.saveChanges();
    //    }).then(function (sr) {
    //        ok(true, "delete succeeded");
    //    }).fail(function (e) {
    //        ok(false, "error on save: " + e.message);
    //    }).fail(testFns.handleFail).fin(start);

    //});

    private Order CreateOrder(EntityManager em) {
      var order = new Order();
      em.AddEntity(order);
      order.ShipName = "Test.NET_" + TestFns.RandomSuffix(7);
      return order;
    }