public void TestUpdateNoSqlErrorHandlerOn()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <TestDbContext>();

            using (var context = new TestDbContext(options))
            {
                context.Database.EnsureCreated();
                context.UniqueEntities.Add(new UniqueEntity {
                    UniqueString = "Hello"
                });
                var entity = new UniqueEntity {
                    UniqueString = "Goodbye"
                };
                context.UniqueEntities.Add(entity);
                context.SaveChanges();

                var utData  = context.SetupSingleDtoAndEntities <UniqueWithConfigDto>();
                var service = new CrudServices(context, utData.ConfigAndMapper);

                //ATTEMPT
                entity.UniqueString = "Hello";
                var ex = Assert.Throws <DbUpdateException>(() => service.UpdateAndSave(entity));

                //VERIFY
                ex.InnerException.Message.ShouldEqual(
                    "SQLite Error 19: 'UNIQUE constraint failed: UniqueEntities.UniqueString'.");
            }
        }
        public async Task TestDtoAccessUpdateWithValidationTurnedOnViaGlobalConfig()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <TestDbContext>();

            using (var context = new TestDbContext(options))
            {
                context.Database.EnsureCreated();
                context.UniqueEntities.Add(new UniqueEntity {
                    UniqueString = "Hello"
                });
                var entity = new UniqueEntity {
                    UniqueString = "Goodbye"
                };
                context.UniqueEntities.Add(entity);
                context.SaveChanges();

                var config = new GenericServicesConfig()
                {
                    DtoAccessValidateOnSave     = true,
                    SaveChangesExceptionHandler = CatchUniqueError19
                };
                var utData  = context.SetupSingleDtoAndEntities <UniqueNoConfigDto>(config);
                var service = new CrudServicesAsync(context, utData.ConfigAndMapper);

                //ATTEMPT
                await service.UpdateAndSaveAsync(new UniqueNoConfigDto()
                {
                    Id = entity.Id, UniqueString = "Hello"
                });

                //VERIFY
                service.GetAllErrors().ShouldEqual("Unique Entity: Unique constraint failed");
            }
        }
        public void TestUpdateCatchSqlErrorOn()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <TestDbContext>();

            using (var context = new TestDbContext(options))
            {
                context.Database.EnsureCreated();
                context.UniqueEntities.Add(new UniqueEntity {
                    UniqueString = "Hello"
                });
                var entity = new UniqueEntity {
                    UniqueString = "Goodbye"
                };
                context.UniqueEntities.Add(entity);
                context.SaveChanges();

                var config = new GenericServicesConfig()
                {
                    SaveChangesExceptionHandler = CatchUniqueError19
                };
                var utData  = context.SetupSingleDtoAndEntities <UniqueWithConfigDto>(config);
                var service = new CrudServices(context, utData.ConfigAndMapper);

                //ATTEMPT
                entity.UniqueString = "Hello";
                service.UpdateAndSave(entity);

                //VERIFY
                service.GetAllErrors().ShouldEqual("Unique constraint failed");
            }
        }
示例#4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldUseConcurrentlyCreatedNode()
        internal virtual void ShouldUseConcurrentlyCreatedNode()
        {
            // given
            GraphDatabaseService graphdb = mock(typeof(GraphDatabaseService));
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") Index<org.neo4j.graphdb.Node> index = mock(Index.class);
            Index <Node> index = mock(typeof(Index));
            Transaction  tx    = mock(typeof(Transaction));

            when(graphdb.BeginTx()).thenReturn(tx);
            when(index.GraphDatabase).thenReturn(graphdb);
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") IndexHits<org.neo4j.graphdb.Node> getHits = mock(IndexHits.class);
            IndexHits <Node> getHits = mock(typeof(IndexHits));

            when(index.get("key1", "value1")).thenReturn(getHits);
            Node createdNode = mock(typeof(Node));

            when(graphdb.CreateNode()).thenReturn(createdNode);
            Node concurrentNode = mock(typeof(Node));

            when(index.PutIfAbsent(createdNode, "key1", "value1")).thenReturn(concurrentNode);
            UniqueFactory.UniqueNodeFactory unique = new UniqueNodeFactoryAnonymousInnerClass(this, index);

            // when
            UniqueEntity <Node> node = unique.GetOrCreateWithOutcome("key1", "value1");

            // then
            assertSame(node.Entity(), concurrentNode);
            assertFalse(node.WasCreated());
            verify(index).get("key1", "value1");
            verify(index).putIfAbsent(createdNode, "key1", "value1");
            verify(graphdb, times(1)).createNode();
            verify(tx).success();
        }
示例#5
0
        public void PreventDuplicatesWhenUnique()
        {
            var name = "John Doe";
            var item = new UniqueEntity()
            {
                Name = name
            };

            _db.UniqueEntities.Add(item);
            Assert.Equal(1, _db.SaveChanges());

            item = new UniqueEntity()
            {
                Name = name
            };

            var context = new ValidationContext(item, _sp, null)
            {
                MemberName = "Name"
            };

            var attrib = item.GetType().GetProperty("Name")?.GetCustomAttribute <IndexAttribute>()
                         ?? throw new InvalidOperationException("Missing attribute.");

            Assert.True(attrib.Unique);

            var result = attrib.GetValidationResult(item.Name, context);

            Assert.NotNull(result);
            Assert.NotEqual(ValidationResult.Success, result);
            Assert.Matches(@"already\sbeen\sused", result.ErrorMessage);
            Assert.Contains("Name", result.MemberNames);

            _db.UniqueEntities.Add(item);

            var x = Assert.Throws <DbUpdateException>(
                () => { _db.SaveChanges(); }
                );

            Assert.NotNull(x.InnerException);
            Assert.Matches("unique", x.InnerException.Message.ToLower());
        }
        public void PreventDuplicatesWhenUnique()
        {
            var a    = 1234;
            var b    = 5678;
            var item = new UniqueEntity()
            {
                Name = "FirstItem", ValueA = a, ValueB = b
            };

            _db.UniqueEntities.Add(item);
            Assert.Equal(1, _db.SaveChanges());

            item = new UniqueEntity()
            {
                Name = "SecondItem", ValueA = a, ValueB = b
            };

            var context = new ValidationContext(item, _sp, null);

            var attrib = item.GetType().GetCustomAttribute <CompositeIndexAttribute>()
                         ?? throw new InvalidOperationException("Missing attribute.");

            Assert.True(attrib.Unique);

            var result = attrib.GetValidationResult(item, context);

            Assert.NotNull(result);
            Assert.NotEqual(ValidationResult.Success, result);
            Assert.Matches(@"already\sbeen\sused", result.ErrorMessage);
            Assert.Contains("ValueA", result.MemberNames);
            Assert.Contains("ValueB", result.MemberNames);

            _db.UniqueEntities.Add(item);

            var x = Assert.Throws <DbUpdateException>(
                () => { _db.SaveChanges(); }
                );

            Assert.NotNull(x.InnerException);
            Assert.Matches("unique", x.InnerException.Message.ToLower());
        }
示例#7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldCreateNodeWithOutcomeAndIndexItIfMissing()
        internal virtual void ShouldCreateNodeWithOutcomeAndIndexItIfMissing()
        {
            // given
            GraphDatabaseService graphdb = mock(typeof(GraphDatabaseService));
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") Index<org.neo4j.graphdb.Node> index = mock(Index.class);
            Index <Node> index = mock(typeof(Index));
            Transaction  tx    = mock(typeof(Transaction));

            when(graphdb.BeginTx()).thenReturn(tx);
            when(index.GraphDatabase).thenReturn(graphdb);
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") IndexHits<org.neo4j.graphdb.Node> indexHits = mock(IndexHits.class);
            IndexHits <Node> indexHits = mock(typeof(IndexHits));

            when(index.get("key1", "value1")).thenReturn(indexHits);
            Node indexedNode = mock(typeof(Node));

            when(graphdb.CreateNode()).thenReturn(indexedNode);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean initializeCalled = new java.util.concurrent.atomic.AtomicBoolean(false);
            AtomicBoolean initializeCalled = new AtomicBoolean(false);

            UniqueFactory.UniqueNodeFactory unique = new UniqueNodeFactoryAnonymousInnerClass3(this, index, initializeCalled);

            // when
            UniqueEntity <Node> node = unique.GetOrCreateWithOutcome("key1", "value1");

            // then
            assertSame(node.Entity(), indexedNode);
            assertTrue(node.WasCreated());
            verify(index).get("key1", "value1");
            verify(index).putIfAbsent(indexedNode, "key1", "value1");
            verify(graphdb, times(1)).createNode();
            verify(tx).success();
            assertTrue(initializeCalled.get(), "Node not initialized");
        }
        //[TestCase(false)]
        public async Task when_inserting_one_duplicate_catched(bool isMongoDbRepo)
        {
            //arrange
            IRepository <UniqueEntity> repository = GetRepositoryToTest <UniqueEntity>(isMongoDbRepo, _dbContext.UniqueEntities);

            //act
            var newEntity = new UniqueEntity
            {
                ID          = ObjectId.GenerateNewId(),
                UniqueValue = "I'm unique"
            };
            bool isDuplicate1 = await repository.InsertOneHandleDuplicate(newEntity);

            newEntity.ID = ObjectId.GenerateNewId();
            bool isDuplicate2 = await repository.InsertOneHandleDuplicate(newEntity);

            //assert
            var actualEntities = await repository.FindAll(x => x.UniqueValue == "I'm unique");

            actualEntities.Should().HaveCount(1);

            isDuplicate2.Should().BeFalse();
            isDuplicate2.Should().BeTrue();
        }
示例#9
0
 public Children(UniqueEntity arg)
     : base(Category.Set, nameof(Children), arg)
 {
 }
示例#10
0
 public void RemoveUnique()
 {
     UniqueEntity.Destroy();
 }
示例#11
0
 public Members(UniqueEntity arg)
     : base(Category.Set, nameof(Members), arg)
 {
 }
示例#12
0
 public Operand(UniqueEntity uniqueEntity)
     : base(uniqueEntity)
 {
 }
示例#13
0
 public static Operand AsOp(this UniqueEntity uniqueEntity)
 => new Operand(uniqueEntity);
示例#14
0
        public int ImportData(string path, int time)
        {
            _logger.Information("IMPORTACAO ESTADOS DE HIV ...");

            UnitOfWork.DbContext.Configuration.AutoDetectChangesEnabled = false;

            FileImporter imp      = new FileImporter();
            string       fullPath = path + @"\HIVStatus.csv";
            DataTable    data     = imp.ImportFromCSV(fullPath);

            String HIVStatusGuidString          = null;
            List <UniqueEntity> BeneficiariesDB = FindAllBeneficiaryUniqueEntities();
            List <UniqueEntity> HIVStatusDB     = HIVStatusQueryService.FindAllHIVStatusUniqueEntity();

            UsersDB = ConvertListToHashtableUsers(findAllUsersUniqueEntities());

            int ImportedHIVStatus = 0;

            try
            {
                foreach (DataRow row in data.Rows)
                {
                    UniqueEntity BeneficiaryUE = null;
                    HIVStatusGuidString = row["HIVStatus_guid"].ToString();
                    Guid      HIVStatusGuid = new Guid(HIVStatusGuidString);
                    HIVStatus HIVStatus     = FindBySyncGuid(HIVStatusDB, new Guid(HIVStatusGuidString)) == null ? new HIVStatus() : findHIVStatusBySyncGuid(HIVStatusGuid);
                    User      user          = (User)UsersDB[new Guid(row["CreatedUserGuid"].ToString())];
                    HIVStatus.CreatedAt            = DateTime.Parse(row["CreatedAt"].ToString());
                    HIVStatus.SyncGuid             = HIVStatusGuid;
                    HIVStatus.HIV                  = row["HIV"].ToString();
                    HIVStatus.NID                  = row["NID"] != null ? row["NID"].ToString() : HIVStatus.NID;
                    HIVStatus.HIVInTreatment       = int.Parse(row["HIVInTreatment"].ToString());
                    HIVStatus.HIVUndisclosedReason = int.Parse(row["HIVUndisclosedReason"].ToString());
                    HIVStatus.InformationDate      = DateTime.Parse(row["InformationDate"].ToString());
                    HIVStatus.SyncDate             = DateTime.Now;
                    HIVStatus.UserID               = user == null ? 1 : user.UserID;

                    if (!isZerosGuid(row["BeneficiaryGuid"].ToString()))
                    {
                        HIVStatus.BeneficiaryGuid = new Guid(row["BeneficiaryGuid"].ToString());
                        BeneficiaryUE             = FindBySyncGuid(BeneficiariesDB, HIVStatus.BeneficiaryGuid);
                        if (BeneficiaryUE != null)
                        {
                            HIVStatus.BeneficiaryID = BeneficiaryUE.ID;
                        }
                    }

                    if (isZerosGuid(row["CreatedUserGuid"].ToString()))
                    {
                        _logger.Error("Nao foi encontrado nenhum usuario com Guid '{0}'. A autoria da criacao deste estado de HIV sera do usuario com ID = 1", row["CreatedUserGuid"].ToString());
                    }

                    // Importamos HIVStatus sem Beneficiarios, pois na criação
                    // ainda não existem beneficiarios importados
                    SaveOrUpdate(HIVStatus);
                    ImportedHIVStatus++;

                    if (ImportedHIVStatus % 100 == 0)
                    {
                        _logger.Information(ImportedHIVStatus + " de " + data.Rows.Count + " estados de HIV importados." + ((time == 1) ? " [Criacao]" : " [Actualizacao]"));
                    }
                }

                UnitOfWork.Commit();
            }
            catch (Exception e)
            {
                _logger.Information("Erro ao importar o Guid {0} ", HIVStatusGuidString);
                _logger.Error(e, "Erro ao importar Estados de HIV", null);
                throw e;
            }
            finally
            {
                if (time == 2)
                {
                    Rename(fullPath, fullPath + IMPORTED);
                    UnitOfWork.Dispose();
                }
            }

            return(ImportedHIVStatus);
        }
示例#15
0
        public int ImportData(string path)
        {
            UnitOfWork.DbContext.Configuration.AutoDetectChangesEnabled = false;
            FileImporter imp     = new FileImporter();
            string       fullPah = path + @"\ChildStatusHistories.csv";

            string                    lastGuidToImport           = null;
            int                       ImportedChildStatusHistory = 0;
            List <User>               UDB                         = UnitOfWork.Repository <User>().GetAll().ToList();
            List <UniqueEntity>       BeneficiariesDB             = FindAllBeneficiaryUniqueEntities();
            List <UniqueEntity>       ChildStatusHistoriesDB      = FindAllChildStatusHistoryUniqueEntities();
            List <ChildStatusHistory> ChildStatusHistoryToPersist = new List <ChildStatusHistory>();
            IEnumerable <DataRow>     ChildStatusRows             = imp.ImportFromCSV(fullPah).Rows.Cast <DataRow>();

            try
            {
                foreach (DataRow row in ChildStatusRows)
                {
                    Guid ChildStatusHistoryGuid = new Guid(row["childstatushistory_guid"].ToString());
                    if (FindBySyncGuid(ChildStatusHistoriesDB, ChildStatusHistoryGuid) == null)
                    {
                        UniqueEntity BeneficiaryUE = null;
                        lastGuidToImport = ChildStatusHistoryGuid.ToString();
                        User user = UDB.Where(x => x.SyncGuid == new Guid(row["CreatedUserGuid"].ToString())).SingleOrDefault();

                        ChildStatusHistory childStatusHistory = new ChildStatusHistory
                        {
                            EffectiveDate = DateTime.Parse(row["EffectiveDate"].ToString()),
                            CreatedDate   = DateTime.Parse(row["CreatedDate"].ToString()),
                            ChildStatusID = int.Parse(row["ChildStatusID"].ToString()),
                            CreatedUserID = user == null ? 1 : user.UserID,
                            SyncGuid      = ChildStatusHistoryGuid,
                            SyncDate      = DateTime.Now
                        };

                        if (!isZerosGuid(row["BeneficiaryGuid"].ToString()))
                        {
                            childStatusHistory.BeneficiaryGuid = new Guid(row["BeneficiaryGuid"].ToString());
                            BeneficiaryUE = FindBySyncGuid(BeneficiariesDB, childStatusHistory.BeneficiaryGuid);
                            if (BeneficiaryUE != null)
                            {
                                childStatusHistory.BeneficiaryID = BeneficiaryUE.ID;
                            }
                        }

                        if (isZerosGuid(row["CreatedUserGuid"].ToString()))
                        {
                            _logger.Error("Não foi encontrado nenhum usuário com Guid '{0}'. A autoria da criacao deste estado sera do usuario com ID = 1", row["CreatedUserGuid"].ToString());
                        }
                        if (BeneficiaryUE == null)
                        {
                            _logger.Error("Estado do Beneficiarios não tem o Guid do Beneficiario, actualmente o valor é '{0}'. O Estado com Guid '{1}' nao sera importado.", row["BeneficiaryGuid"].ToString(), ChildStatusHistoryGuid);
                        }
                        else
                        {
                            ChildStatusHistoryToPersist.Add(childStatusHistory);
                            ImportedChildStatusHistory++;
                        }
                    }

                    if (ImportedChildStatusHistory % 100 == 0)
                    {
                        _logger.Information(ImportedChildStatusHistory + " de " + ChildStatusRows.Count() + " Estados de Crianca importados.");
                    }
                }
                ChildStatusHistoryToPersist.ForEach(csh => UnitOfWork.Repository <ChildStatusHistory>().Add(csh));
                UnitOfWork.Commit();
                Rename(fullPah, fullPah + IMPORTED);
            }
            catch (Exception e)
            {
                _logger.Information("Erro ao importar o Guid : " + lastGuidToImport);
                _logger.Error(e, "Erro ao importar Criancas", null);
                throw e;
            }

            return(ChildStatusHistoryToPersist.Count());
        }
示例#16
0
 protected TailFunction(Category category, string name, UniqueEntity arg)
     : base(Type.Tail, category, name)
     => Body = $"{arg}.{Name}";