コード例 #1
0
        public void TestCreateOneEntry()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <Chapter3DbContext>();

            using (var context = new Chapter3DbContext(options))
            {
                context.Database.EnsureCreated();
                var itemToAdd = new ExampleEntity
                {
                    MyMessage = "Hello World"
                };

                //ATTEMPT
                context.Add(itemToAdd); //#A
                context.SaveChanges();  //#B

                /*********************************************************
                 #A It use the Add method to add the SingleEntity to the application's DbContext. The DbContext works what table to add it to based on its type of its parameter
                 #B It calls the SaveChanges() method from the application's DbContext to update the database
                 * ***********************************************************/

                //VERIFY
                context.SingleEntities.Count()
                .ShouldEqual(1);
                itemToAdd.ExampleEntityId
                .ShouldNotEqual(0);
            }
        }
コード例 #2
0
        public async Task <ActionResult <ExampleEntity> > Add(ExampleEntity entitiy)
        {
            _context.Add(entitiy);
            await _context.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetExampleEntityById), new { id = entitiy.ExampleId }, entitiy));
        }
コード例 #3
0
        public void TestCreateOneEntrySqlServerWithLogs()
        {
            //SETUP
            var connection     = this.GetUniqueDatabaseConnectionString();
            var optionsBuilder =
                new DbContextOptionsBuilder <SimpleDbContext>();

            optionsBuilder.UseSqlServer(connection);
            var logs = new List <string>();

            using (var context = new SimpleDbContext(optionsBuilder.Options))
            {
                context.Database.EnsureCreated();
                SqliteInMemory.SetupLogging(context, logs);

                var itemToAdd = new ExampleEntity
                {
                    MyMessage = "Hello World"
                };

                //ATTEMPT
                context.SingleEntities.Add(
                    itemToAdd);
                context.SaveChanges();

                //VERIFY
                foreach (var log in logs)
                {
                    _output.WriteLine(log);
                }
            }
        }
コード例 #4
0
        public void TestCreateOneEntryWithLogs()
        {
            //SETUP
            var showLog = false;
            var options = SqliteInMemory.CreateOptionsWithLogging <Chapter3DbContext>(log =>
            {
                if (showLog)
                {
                    _output.WriteLine(log.DecodeMessage());
                }
            });

            using (var context = new Chapter3DbContext(options))
            {
                context.Database.EnsureCreated();

                showLog = true;
                var itemToAdd = new ExampleEntity
                {
                    MyMessage = "Hello World"
                };

                //ATTEMPT
                context.SingleEntities.Add(
                    itemToAdd);
                context.SaveChanges();

                //VERIFY
                context.SingleEntities.Count().ShouldEqual(1);
            }
        }
        public void SetNameValidLength()
        {
            var exampleEntity = new ExampleEntity();

            exampleEntity.SetName("new name");
            Assert.Equal(true, exampleEntity.IsValid());
        }
コード例 #6
0
        public void Persist_Compression()
        {
            var session = SessionFactoryProvider.Instance.OpenSession();

            JsonCompressor.CompressionThreshold = 10;
            var id        = 12;
            var identifer = Guid.NewGuid();
            var repo      = new ExampleEntityRepository(session);
            var entity    = new ExampleEntity(id, "Something", new ExampleJsonModel(identifer, new List <string> {
                "AAAAAA", "BBBBBBBB", "CCCCCCC", "DDDDDDD"
            }));

            repo.Save(entity);
            repo.Flush();

            var found = repo.FindAll();

            Assert.Equal(1, found.Count);

            Assert.Equal(id, entity.Id);
            Assert.Equal("Something", found.First().Title);
            Assert.Equal(identifer, entity.Json.Identifier);
            Assert.Equal("AAAAAA", entity.Json.List.First());
            session.Dispose();
            JsonCompressor.CompressionThreshold = 10000;
        }
コード例 #7
0
        public ExampleModule(IRepositoryOfId <int> repository, IMappingEngine engine, ExampleSender sender)
        {
            Get["/examples"] = _ => repository.Query <ExampleEntity>()
                               .Project().To <ExampleModel>()
                               .ToList();

            Get["/example/{id:int}"] = _ => {
                var entity = repository.Load <ExampleEntity>(_.id);
                return(engine.Map <ExampleEntity, ExampleModel>(entity));
            };

            Post["/examples"] = _ => {
                var model  = this.BindAndValidateModel <NewExampleModel>();
                var entity = new ExampleEntity(model.Name);
                repository.Save(entity);

                return(new NewExampleCreatedModel {
                    Id = entity.ID
                });
            };

            Post["/examples/close"] = _ => {
                var model = this.BindAndValidateModel <CloseExampleModel>();

                sender.CloseExample(model.Id);

                return(HttpStatusCode.OK);
            };

            Delete["/example/{id:int}"] = _ => {
                repository.Delete <ExampleEntity>(_.id);
                return(HttpStatusCode.OK);
            };
        }
コード例 #8
0
        public List <ExampleEntity> GetAll()
        {
            List <ExampleEntity> results = null;

            dataProvider.ExecuteCmd(
                "example_entity__getall",
                inputParamMapper : null,
                singleRecordMapper : delegate(IDataReader reader, short set)
            {
                if (results == null)
                {
                    results = new List <ExampleEntity>();
                }

                // In English this means:
                // create a new variable called result that can hold an object of type
                // ExampleEntity. THEN, create a new instance of ExampleEntity and
                // store it in that variable.
                ExampleEntity result = new ExampleEntity();

                result.Id           = reader.GetInt32(0);
                result.DateCreated  = reader.GetDateTime(1);
                result.DateModified = reader.GetDateTime(2);
                result.Thing        = reader.GetInt32(3);
                result.Stuff        = reader.GetString(4);

                results.Add(result);
            });

            return(results);
        }
コード例 #9
0
        public void should_save_and_load_example()
        {
            var entity    = new ExampleEntity("test");
            var newEntity = VerifyPersistence(entity);

            newEntity.ShouldBeEquivalentTo(entity, DefaultCompareConfig.Compare);
        }
コード例 #10
0
    /// <summary>
    /// Copies components on this entity at <paramref name="indices"/> in the <see cref="ExampleComponentsLookup"/> to
    /// <paramref name="copyToEntity"/>. If <paramref name="replaceExisting"/> is true any of the components that
    /// <paramref name="copyToEntity"/> has that this entity has will be replaced, otherwise they will be skipped.
    /// </summary>
    public void CopyTo(ExampleEntity copyToEntity, bool replaceExisting, params int[] indices)
    {
        for (var i = 0; i < indices.Length; ++i)
        {
            var index = indices[i];

            // Validate that the index is within range of the component lookup
            if (index < 0 && index >= ExampleComponentsLookup.TotalComponents)
            {
                const string OUT_OF_RANGE_WARNING =
                    "Component Index [{0}] is out of range for [{1}].";

                const string HINT = "Please ensure any CopyTo indices are valid.";

                throw new IndexOutOfLookupRangeException(
                          string.Format(OUT_OF_RANGE_WARNING, index, nameof(ExampleComponentsLookup)),
                          HINT);
            }

            if (!HasComponent(index))
            {
                continue;
            }

            if (!copyToEntity.HasComponent(index) || replaceExisting)
            {
                var component = GetComponent(index);
                copyToEntity.CopyComponentTo(component);
            }
        }
    }
コード例 #11
0
        public void TestCreateOneEntryWithLogs()
        {
            //SETUP
            var logs = new List <string>();

            using (var context = new SimpleDbContext(
                       SqliteInMemory.CreateOptions <SimpleDbContext>()))
            {
                context.Database.EnsureCreated();
                SqliteInMemory.SetupLogging(context, logs);

                var itemToAdd = new ExampleEntity
                {
                    MyMessage = "Hello World"
                };

                //ATTEMPT
                context.SingleEntities.Add(
                    itemToAdd);
                context.SaveChanges();

                //VERIFY
                context.SingleEntities.Count()
                .ShouldEqual(1);
                foreach (var log in logs)
                {
                    _output.WriteLine(log);
                }
            }
        }
コード例 #12
0
        public void IsPersisted_WHERE_entity_is_not_persisted_SHOULD_return_false()
        {
            //act
            var actual = new ExampleEntity();

            //assert
            Assert.That(actual.IsPersisted, Is.False);
        }
コード例 #13
0
        private ExampleEntityViewModel Map(ExampleEntity entity)
        {
            var result = new ExampleEntityViewModel {
                Id = entity.Id, Name = entity.Name
            };

            return(result);
        }
コード例 #14
0
        public void Equals_NewHeapAddressAndId()
        {
            var e1 = new ExampleEntity();
            var e2 = new ExampleEntity(1);

            Assert.NotEqual(e1, e2);
            Assert.False(e1 == e2);
            Assert.True(e1 != e2);
        }
コード例 #15
0
        public void Equals_AnotherHeapAddress()
        {
            var e1 = new ExampleEntity();
            var e2 = new ExampleEntity();

            Assert.NotEqual(e1, e2);
            Assert.False(e1 == e2);
            Assert.True(e1 != e2);
        }
        public void SetNameInvalidMinLength()
        {
            var exampleEntity = new ExampleEntity();

            exampleEntity.Errors.Clear();
            exampleEntity.SetName(stringUtils.RandomString(PropertyLength.ExampleEntity_Name_MinLength - 1));

            Assert.Equal(false, exampleEntity.IsValid());
        }
コード例 #17
0
        public void Equals_BothNull()
        {
            ExampleEntity e1 = null;
            ExampleEntity e2 = null;

            Assert.Equal(e1, e2);
            Assert.True(e1 == e2);
            Assert.False(e1 != e2);
        }
コード例 #18
0
        public void Equals_DifferentIds()
        {
            var e1 = new ExampleEntity(1);
            var e2 = new ExampleEntity(2);

            Assert.NotEqual(e1, e2);
            Assert.False(e1 == e2);
            Assert.True(e1 != e2);
        }
コード例 #19
0
        public void Equals_SameHeapAddress()
        {
            var e1 = new ExampleEntity();
            var e2 = e1;

            Assert.Equal(e1, e2);
            Assert.True(e1 == e2);
            Assert.False(e1 != e2);
        }
コード例 #20
0
        public void Equals_IdAndNull()
        {
            var           e1 = new ExampleEntity(1);
            ExampleEntity e2 = null;

            Assert.NotEqual(e1, e2);
            Assert.False(e1 == e2);
            Assert.True(e1 != e2);
        }
コード例 #21
0
        public void Equals_NewHeapAddressAndNull()
        {
            ExampleEntity e1 = null;
            var           e2 = new ExampleEntity();

            Assert.NotEqual(e1, e2);
            Assert.False(e1 == e2);
            Assert.True(e1 != e2);
        }
        public ExampleEntity Build()
        {
            var result = new ExampleEntity();

            result.SetName(Name);
            result.SetId(Guid.NewGuid());

            return(result);
        }
コード例 #23
0
 internal static void Update(this ExampleEntity entity, ExampleEntityDto dto, DbContext context, string modifiedBy, DateTime modifiedDate)
 {
     if (entity != null && dto != null)
     {
         entity.ExampleProperty = dto.ExampleProperty;
         entity.ModifiedDate    = modifiedDate;
         entity.ModifiedBy      = modifiedBy;
     }
 }
コード例 #24
0
        public void should_create_example_entity()
        {
            var now    = DateTime.Now;
            var entity = new ExampleEntity(NAME);

            entity.Name.Should().Be(NAME);
            entity.Status.Should().Be(ExampleStatus.Open);
            entity.Timestamp.DateCreated.Should().BeWithin(1.Seconds()).After(now);
            entity.Timestamp.DateUpdated.Should().BeWithin(1.Seconds()).After(now);
        }
        public void WhenWeHaveASourceObject_ThenWeCanMapToADestinationObject()
        {
            var entity = new ExampleEntity {
                Id = Guid.NewGuid()
            };
            var mapper = new ExampleEntityMapper();
            var dto    = mapper.Map(entity);

            Assert.Equal(entity.Id, dto.Id);
        }
コード例 #26
0
        public ExampleEntity GetById(int id)
        {
            ExampleEntity result = null;

            /*
             *
             * // This is the plain-vanilla ADO.NET version of the dataProvider call below
             *
             * using (SqlConnection con = new SqlConnection("..."))
             * {
             *  con.Open();
             *
             *  SqlCommand cmd = con.CreateCommand();
             *  cmd.CommandText = "example_entity__getbyid"; // #1
             *  cmd.CommandType = CommandType.StoredProcedure;
             *
             *  cmd.Parameters.AddWithValue("@id", id); // #2
             *
             *  using (IDataReader reader = cmd.ExecuteReader())
             *  {
             *      if (reader.Read())
             *      {
             *          result = new ExampleEntity(); // #3
             *          result.Id = id;
             *          result.DateCreated = reader.GetDateTime(0);
             *          result.DateModified = reader.GetDateTime(1);
             *          result.Stuff = reader.GetString(2);
             *          result.Thing = reader.GetInt32(3);
             *      }
             *  }
             * }
             *
             * return result;
             */

            dataProvider.ExecuteCmd(
                "example_entity__getbyid", // #1
                inputParamMapper : delegate(SqlParameterCollection parameters)
            {
                parameters.AddWithValue("@id", id);     // #2
            },
                singleRecordMapper : delegate(IDataReader reader, short set)
            {
                result              = new ExampleEntity(); // #3
                result.Id           = reader.GetInt32(0);
                result.DateCreated  = reader.GetDateTime(1);
                result.DateModified = reader.GetDateTime(2);
                result.Stuff        = reader.GetString(3);
                result.Thing        = reader.GetInt32(4);
            }
                );

            return(result);
        }
コード例 #27
0
        public void WhenWeHaveASourceObject_ThenWeCanMapToADestinationObject()
        {
            var autoMapper = new AutoMapperFactory().CreateMapper();
            var entity     = new ExampleEntity {
                Id = Guid.NewGuid()
            };
            var mapper = new AutoMapperAdapter <ExampleEntity, ExampleDto>(autoMapper);
            var dto    = mapper.Map(entity);

            Assert.Equal(entity.Id, dto.Id);
        }
コード例 #28
0
 public IActionResult InsertExampleEntity([FromBody] ExampleEntity entity)
 {
     try
     {
         var result = _repository.Insert(entity);
         return(CreatedAtRoute("", new { id = entity.ID }, result));
     }
     catch (Exception exception)
     {
         return(StatusCode(500, exception));
     }
 }
コード例 #29
0
        public void should_update_status_to_closed()
        {
            var created = DateTime.Now;
            var entity  = new ExampleEntity(NAME);

            var updated = DateTime.Now;

            entity.Close();

            entity.Status.Should().Be(ExampleStatus.Closed);
            entity.Timestamp.DateCreated.Should().BeWithin(1.Seconds()).After(created);
            entity.Timestamp.DateUpdated.Should().BeWithin(1.Seconds()).After(updated);
        }
コード例 #30
0
        public async Task DeleteAsync(string id)
        {
            await using var context = new DatabaseContext(_dbContextOptionsBuilder.Options);

            var example = new ExampleEntity {
                Id = id
            };

            context.Examples.Attach(example);
            context.Examples.Remove(example);

            await context.SaveChangesAsync();
        }
コード例 #31
0
        public EntityPlatform(ExampleEntity entity, EarthCentralBody earth, string dataPath)
        {
            //id, string
            m_id = entity.EntityIdentifier.ToString();

            //name, string
            string name = entity.Marking.ToString();

            //Last Update, DateTime
            DateTime time = DateTime.Parse(entity.LastUpdateDateTime.ToString());

            //Position, Cartesian
            string[] xyz = entity.Position.ToString().Split(',');
            Cartesian position = new Cartesian(Convert.ToDouble(xyz[0]), Convert.ToDouble(xyz[1]), Convert.ToDouble(xyz[2]));

            m_platform = new Platform();
            m_platform.Name = name;
            m_platform.LocationPoint = new PointCartographic(earth, earth.Shape.CartesianToCartographic(position));
            m_platform.OrientationAxes = new AxesVehicleVelocityLocalHorizontal(earth.FixedFrame, m_platform.LocationPoint);

            LabelGraphicsExtension labelExtension = new LabelGraphicsExtension(new LabelGraphics
            {
                Text = new ConstantCesiumProperty<string>(name),
                Scale = new ConstantCesiumProperty<double>(0.5),
                FillColor = new ConstantCesiumProperty<Color>(Color.White),
                PixelOffset = new ConstantCesiumProperty<Rectangular>(new Rectangular(35, -15))
            });
            m_platform.Extensions.Add(labelExtension);

            string symbol = entity.Symbology.ToString().Replace('*', '_') + ".png";
            CesiumResource billboardResource = new CesiumResource(new Uri(dataPath + symbol), CesiumResourceBehavior.LinkTo);
            BillboardGraphicsExtension billboardExtension = new BillboardGraphicsExtension(new BillboardGraphics
            {
                Image = new ConstantCesiumProperty<CesiumResource>(billboardResource),
                Show = true,
                Scale = new ConstantCesiumProperty<double>(1)
            });
            m_platform.Extensions.Add(billboardExtension);

            m_czmlDocument = new CzmlDocument();
            m_czmlDocument.Name = "Realtime";
            m_czmlDocument.RequestedInterval = new TimeInterval(new JulianDate(DateTime.Now), new JulianDate(DateTime.Now.AddDays(1.0)));
            m_czmlDocument.Clock = new Clock
            {
                Step = ClockStep.SystemClock
            };

            m_czmlDocument.ObjectsToWrite.Add(m_platform);
        }
コード例 #32
0
        private void WorkerThread()
        {
            while (m_active)
            {
                JulianDate time = new JulianDate(DateTime.UtcNow);

                //FIXED WIDTH FORMAT
                //ID(12) X(20) Y(20) Z(20) QX(20) QY(20) QZ(20) QW(20) Marking(12) Symbology(16) Force(2)
                string[] records = File.ReadAllLines(Path.Combine(m_dataPath, "surveillance.txt"));

                foreach (string record in records)
                {
                    if (!m_active)
                    {
                        break;
                    }

                    string entityID = record.Substring(0, 12).Trim();
                    int delay = int.Parse(record.Substring(12, 4).Trim(), CultureInfo.InvariantCulture);
                    double x = double.Parse(record.Substring(16, 20).Trim(), CultureInfo.InvariantCulture);
                    double y = double.Parse(record.Substring(36, 20).Trim(), CultureInfo.InvariantCulture);
                    double z = double.Parse(record.Substring(56, 20).Trim(), CultureInfo.InvariantCulture);
                    double qx = double.Parse(record.Substring(76, 20).Trim(), CultureInfo.InvariantCulture);
                    double qy = double.Parse(record.Substring(96, 20).Trim(), CultureInfo.InvariantCulture);
                    double qz = double.Parse(record.Substring(116, 20).Trim(), CultureInfo.InvariantCulture);
                    double qw = double.Parse(record.Substring(136, 20).Trim(), CultureInfo.InvariantCulture);
                    string marking = record.Substring(156, 12).Trim();
                    string symbology = record.Substring(168, 16).Trim();
                    Force force = (Force)int.Parse(record.Substring(184, 2).Trim(), CultureInfo.InvariantCulture);

                    m_entities.Context.DoTransactionally(
                        delegate(Transaction transaction)
                        {
                            ExampleEntity entity = m_entities.GetEntityById(transaction, entityID);
                            if (entity == null)
                            {
                                entity = new ExampleEntity(m_entities.Context, entityID);
                                m_entities.Add(transaction, entity);
                            }

                            entity.LastUpdate.SetValue(transaction, time);
                            entity.LastUpdateDateTime.SetValue(transaction, time.ToDateTime());
                            entity.Marking.SetValue(transaction, marking);
                            entity.Orientation.SetValue(transaction, new UnitQuaternion(qw, qx, qy, qz));
                            entity.Position.SetValue(transaction, new Cartesian(x, y, z));
                            entity.Affiliation.SetValue(transaction, force);
                            entity.Symbology.SetValue(transaction, symbology);
                        });

                    if (delay > 0)
                    {
                        //Remove anything that hasn't been updated.

                        m_entities.Context.DoTransactionally(
                            delegate(Transaction transaction)
                            {
                                foreach (ExampleEntity entity in m_entities.GetEntities(transaction))
                                {
                                    if (time.Subtract(entity.LastUpdate.GetValue(transaction)).TotalSeconds > .5)
                                    {
                                        m_entities.Remove(transaction, entity);
                                    }
                                }
                            });

                        Thread.Sleep(delay);
                        time = time.AddSeconds((double)delay / 1000.0);
                    }
                }
            }
        }