Exemple #1
0
        public async Task <Uri> Create(AnyEntity entity)
        {
            entity.Id = "0"; //Реализовано инкрементом
            var uri = await webApiHelper.CreateAnyEntityAsync(entity);

            return(uri); //В релизе, конечно, что-то осмысленное
        }
        public IHttpActionResult PutAnyEntity(int id, AnyEntity anyEntity)
        {
            if (IsInRole("Admin"))
            {
                if (id != anyEntity.Id)
                {
                    return(BadRequest());
                }

                try
                {
                    using (ISession session = NHibernateSession.OpenSession())
                    {
                        using (ITransaction transaction = session.BeginTransaction())
                        {
                            session.SaveOrUpdate(anyEntity);
                            transaction.Commit();
                        }
                    }
                }
                catch (Exception e)
                {
                    throw;
                }

                return(StatusCode(HttpStatusCode.NoContent));
            }

            return(Content(HttpStatusCode.Unauthorized, "Редактирование позволено только роли Admin"));
        }
        public IHttpActionResult PostAnyEntity(AnyEntity anyEntity)
        {
            if (IsInRole("Admin"))
            {
                try
                {
                    using (ISession session = NHibernateSession.OpenSession())
                    {
                        using (ITransaction transaction = session.BeginTransaction())
                        {
                            session.Save(anyEntity);
                            transaction.Commit();
                        }
                    }
                }
                catch (Exception e)
                {
                    throw;
                }

                return(CreatedAtRoute("DefaultApi", new { id = anyEntity.Id }, anyEntity));
            }

            return(Content(HttpStatusCode.Unauthorized, "Вставка позволена только роли Admin"));
        }
Exemple #4
0
        public async Task Update_ExistingEntityWithAutoSave_EntityUpdated()
        {
            using var dbContextProvider = new AnyDbContextProvider(nameof(Update_ExistingEntityWithAutoSave_EntityUpdated));
            var repository = new AnyRepository(dbContextProvider.DbContext, _logger)
            {
                AutoSave = true
            };

            dbContextProvider.Mock(new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            });
            var expected = new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyNewString"
            };

            await repository.Update(expected);

            var actual = repository.Get(1);

            actual.Single().Should().BeEquivalentTo(expected);
        }
        public IHttpActionResult DeleteAnyEntity(int id)
        {
            if (IsInRole("Admin"))
            {
                AnyEntity anyEntity = null;
                try
                {
                    using (ISession session = NHibernateSession.OpenSession())
                    {
                        anyEntity = session.Get <AnyEntity>(id);
                        if (anyEntity == null)
                        {
                            return(NotFound());
                        }

                        using (ITransaction transaction = session.BeginTransaction())
                        {
                            session.Delete(anyEntity);
                            transaction.Commit();
                        }
                    }
                }
                catch (Exception e)
                {
                    throw;
                }

                return(Ok(anyEntity));
            }

            return(Content(HttpStatusCode.Unauthorized, "Удаление позволено только роли Admin"));
        }
        public async Task Create_CreateForbidden_ReturnsForbidden()
        {
            // Arrange
            var restrictedController = new AnyAsyncReadOnlyController(repository, logger);
            var entity = new AnyEntity();

            // Act
            var result = await restrictedController.Create(entity) as ObjectResult;

            // Assert
            result.Should().NotBeNull();
            result.StatusCode.Should().Be(403);
            A.CallTo(() => repository.Create(entity)).MustNotHaveHappened();
        }
        public void Create_AnyEntity_EntityCreated()
        {
            // Arrange
            var expected = new AnyEntity
            {
                AnyString = "AnyString"
            };

            // Act
            repository.Create(expected);
            dbContext.SaveChanges();

            // Assert
            dbContext.AnyEntities.First().AnyString.Should().Be(expected.AnyString);
        }
        public async Task Update_AnyEntityWithoutId_Returns400BadRequest()
        {
            // Arrange
            var entity = new AnyEntity
            {
                AnyString = "AnyString"
            };

            // Act
            var result = await controller.Update(1, entity) as BadRequestObjectResult;

            // Assert
            result.Should().NotBeNull();
            A.CallTo(() => repository.UpdateAsync(1, entity)).MustNotHaveHappened();
        }
        public async Task Create_AnyEntity_RepositoryCreatesEntity()
        {
            // Arrange
            var entity = new AnyEntity
            {
                AnyString = "AnyString"
            };

            // Act
            var result = await controller.Create(entity) as OkResult;

            // Assert
            result.Should().NotBeNull();
            A.CallTo(() => repository.Create(entity)).MustHaveHappenedOnceExactly();
        }
        public void SaveChangesAsync_NoCallAfterAdd_ChangesNotSaved()
        {
            // Arrange
            var entity = new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            };

            // Act
            dbContext.AnyEntities.Add(entity);

            // Assert
            dbContext.AnyEntities.Should().BeEmpty();
        }
        public void Update_UpdateForbidden_ReturnsForbidden()
        {
            // Arrange
            var restrictedController = new AnyReadOnlyController(repository, logger);
            int id     = 1;
            var entity = new AnyEntity();

            // Act
            var result = restrictedController.Update(id, entity) as ObjectResult;

            // Assert
            result.Should().NotBeNull();
            result.StatusCode.Should().Be(403);
            A.CallTo(() => repository.Update(id, entity)).MustNotHaveHappened();
        }
Exemple #12
0
        public async Task Create_ExistingEntity_ThrowsArgumentException()
        {
            using var dbContextProvider = new AnyDbContextProvider(nameof(Create_ExistingEntity_ThrowsArgumentException));
            var repository = new AnyRepository(dbContextProvider.DbContext, _logger);
            var entity     = new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            };

            dbContextProvider.Mock(entity);

            await repository.Create(entity);

            await repository.Invoking(r => r.SaveChanges()).Should().ThrowAsync <ArgumentException>();
        }
        public async Task SaveChangesAsync_CallAfterAdd_ChangesSaved()
        {
            // Arrange
            var expected = new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            };

            // Act
            dbContext.AnyEntities.Add(expected);
            await repository.SaveChangesAsync();

            // Assert
            dbContext.AnyEntities.First().Should().BeEquivalentTo(expected);
        }
        public void Update_AnyEntity_RepositoryUpdatesEntity()
        {
            // Arrange
            var entity = new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            };

            // Act
            var result = controller.Update(1, entity) as OkResult;

            // Assert
            result.Should().NotBeNull();
            A.CallTo(() => repository.Update(1, entity)).MustHaveHappenedOnceExactly();
        }
        public async Task Create_AnyEntityWithId_Returns400BadRequest()
        {
            // Arrange
            var entity = new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            };

            // Act
            var result = await controller.Create(entity) as BadRequestObjectResult;

            // Assert
            result.Should().NotBeNull();
            result.StatusCode.Should().Be(400);
            A.CallTo(() => repository.Create(entity)).MustNotHaveHappened();
        }
Exemple #16
0
        public async Task Create_AnyEntityWithAutoSave_EntityCreated()
        {
            using var dbContextProvider = new AnyDbContextProvider(nameof(Create_AnyEntityWithAutoSave_EntityCreated));
            var repository = new AnyRepository(dbContextProvider.DbContext, _logger);
            var expected   = new AnyEntity
            {
                AnyString = "AnyString"
            };

            repository.AutoSave = true;

            await repository.Create(expected);

            var actual = repository.GetAll();

            actual.Single().AnyString.Should().Be(expected.AnyString);
        }
Exemple #17
0
 public double X(int entityId)
 {
     try
     {
         AnyEntity entity        = simulation.GetEntity(entityId);
         dynamic   dynamicEntity = entity;
         return((double)dynamicEntity.X);
     }
     catch (RuntimeBinderException)
     {
         return(0);
     }
     catch (KeyNotFoundException)
     {
         return(0);
     }
 }
        public async Task UpdateAsync_NonExistingEntity_ThrowsKeyNotFoundException()
        {
            // Arrange
            dbContext.AnyEntities.Add(new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            });
            dbContext.SaveChanges();
            var updatedEntity = new AnyEntity
            {
                AnyString = "AnyNewString"
            };

            // Act & Assert
            await repository.Awaiting(r => r.UpdateAsync(2, updatedEntity)).Should().ThrowAsync <KeyNotFoundException>();
        }
        public void Update_NonExistingEntity_ThrowsKeyNotFoundException()
        {
            // Arrange
            dbContext.AnyEntities.Add(new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            });
            dbContext.SaveChanges();
            var updatedEntity = new AnyEntity
            {
                AnyString = "AnyNewString"
            };

            // Act & Assert
            repository.Invoking(r => r.Update(2, updatedEntity)).Should().Throw <KeyNotFoundException>();
        }
Exemple #20
0
        public static double Q(Simulation simulation, int entityId)
        {
            if (!simulation.Entities.ContainsKey(entityId))
            {
                return(0);
            }

            AnyEntity entity = simulation.GetEntity(entityId);

            if (entity is QueueEntity)
            {
                return(((QueueEntity)entity).Q);
            }
            else
            {
                throw new ModelingException("SNA::Q: Entity is not a Queue. EntityId: " + entityId);
            }
        }
Exemple #21
0
        public static double X(Simulation simulation, int entityId)
        {
            if (!simulation.Entities.ContainsKey(entityId))
            {
                return(0);
            }

            AnyEntity entity = simulation.GetEntity(entityId);

            if (entity is SavevalueEntity)
            {
                return((double)((SavevalueEntity)entity).X);
            }
            else
            {
                throw new ModelingException("SNA::X: Entity is not a Savevalue. EntityId: " + entityId);
            }
        }
Exemple #22
0
        public static double SF(Simulation simulation, int entityId)
        {
            if (!simulation.Entities.ContainsKey(entityId))
            {
                return(0);
            }

            AnyEntity entity = simulation.GetEntity(entityId);

            if (entity is StorageEntity)
            {
                return(((StorageEntity)entity).SF);
            }
            else
            {
                throw new ModelingException("SNA::SF: Entity is not a Storage. EntityId: " + entityId);
            }
        }
        public void Create_ExistingEntity_ThrowsArgumentException()
        {
            // Arrange
            var entity = new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            };

            dbContext.AnyEntities.Add(entity);
            dbContext.SaveChanges();

            // Act
            repository.Create(entity);

            // Assert
            dbContext.Invoking(db => db.SaveChanges()).Should().Throw <ArgumentException>();
        }
        public async Task Update_AnyNonExistingEntity_Returns404NotFound()
        {
            // Arrange
            var entity = new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            };

            A.CallTo(() => repository.UpdateAsync(1, entity)).Throws <KeyNotFoundException>();

            // Act
            var result = await controller.Update(1, entity) as NotFoundObjectResult;

            // Assert
            result.Should().NotBeNull();
            result.StatusCode.Should().Be(404);
        }
        public async Task Read_AnyId_ReturnsEntityFromRepository()
        {
            // Arrange
            var expected = new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            };

            A.CallTo(() => repository.GetAsync(1)).Returns(expected);

            // Act
            var result = (await controller.Read(1)).Result as OkObjectResult;

            // Assert
            result.Should().NotBeNull();
            result.Value.Should().Be(expected);
        }
        public void SaveChangesAsync_NoCallAfterRemove_ChangesNotSaved()
        {
            // Arrange
            var entity = new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            };

            dbContext.Add(entity);
            dbContext.SaveChanges();
            dbContext.AnyEntities.Should().Contain(entity);

            // Act
            dbContext.AnyEntities.Remove(entity);

            // Assert
            dbContext.AnyEntities.Should().Contain(entity);
        }
Exemple #27
0
        public void Copy_EntityNotDerivedFromBaseAuditedEntity_ThrowsArgumentException()
        {
            var original = new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            };
            var newEntity = new AnyAuditedEntity
            {
                Id        = 2,
                AnyString = "AnyString",
                CreatedAt = DateTime.UtcNow,
                CreatedBy = 2,
                UpdatedAt = DateTime.UtcNow,
                UpdatedBy = 3
            };

            newEntity.Invoking(e => e.Copy(original)).Should().Throw <ArgumentException>();
        }
        public void Copy_AnyEntity_ValuesCopied()
        {
            // Arrange
            var original = new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            };
            var newEntity = new AnyEntity
            {
                AnyString = "AnyOtherString"
            };

            // Act
            newEntity.Copy(original);

            // Assert
            newEntity.AnyString.Should().Be(original.AnyString);
        }
        public async Task SaveChangesAsync_CallAfterRemove_ChangesSaved()
        {
            // Arrange
            var entity = new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            };

            dbContext.Add(entity);
            dbContext.SaveChanges();
            dbContext.AnyEntities.Should().Contain(entity);

            // Act
            dbContext.AnyEntities.Remove(entity);
            await repository.SaveChangesAsync();

            // Assert
            dbContext.AnyEntities.Should().BeEmpty();
        }
        public void Copy_WithNewId_IdIgnored()
        {
            // Arrange
            var original = new AnyEntity
            {
                Id        = 1,
                AnyString = "AnyString"
            };
            var newEntity = new AnyEntity
            {
                Id        = 2,
                AnyString = "AnyOtherString"
            };

            // Act
            newEntity.Copy(original);

            // Assert
            newEntity.Id.Should().Be(newEntity.Id);
            newEntity.AnyString.Should().Be(original.AnyString);
        }