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

            using (var context = new EfCoreContext(options))
            {
                context.Database.EnsureCreated();
                context.SeedDatabaseFourBooks();
                var firstBook = context.Books.First();
                var status    = Order.CreateOrder("J", DateTime.Today,
                                                  new List <OrderBooksDto> {
                    new OrderBooksDto(firstBook.BookId, firstBook, 1)
                });
                context.Add(status.Result);

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

                //ATTEMPT
                service.DeleteAndSave <Book>(firstBook.BookId);

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

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

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

                //ATTEMPT
                service.CreateAndSave(new NormalEntity {
                    MyString = "bad word"
                });

                //VERIFY
                service.IsValid.ShouldBeFalse();
                service.GetAllErrors().ShouldEqual("The NormalEntity class contained a bad word.");
            }
            using (var context = new TestDbContext(options))
            {
                context.NormalEntities.Count().ShouldEqual(0);
            }
        }
        public void 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 CrudServices(context, utData.ConfigAndMapper);

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

                //VERIFY
                service.GetAllErrors().ShouldEqual("Unique Entity: Unique constraint failed");
            }
        }
        public async Task 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 CrudServicesAsync(context, utData.ConfigAndMapper, new CreateNewDBContextHelper(() => new TestDbContext(options)));

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

                //VERIFY
                service.GetAllErrors().ShouldEqual("Unique constraint failed");
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// This will take an IQueryable request and add single on the end to realise the request.
        /// It catches if the single didn't produce an item
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request">An IQueryable request with a filter that yeilds a single item</param>
        /// <param name="methodName">Do not specify. System fills this in with the calling method</param>
        /// <returns>Returns status. If Valid then status.Result is the single item, otherwise an new, empty class</returns>
        public static ISuccessOrErrors <T> RealiseSingleWithErrorChecking <T>(this IQueryable <T> request, [CallerMemberName] string methodName = "") where T : class, new()
        {
            var status = new SuccessOrErrors <T>(new T(), "we return empty class if it fails");

            try
            {
                var result = request.SingleOrDefault();
                if (result == null)
                {
                    status.AddSingleError(
                        "We could not find an entry using that filter. Has it been deleted by someone else?");
                }
                else
                {
                    status.SetSuccessWithResult(result, "successful");
                }
            }
            catch (Exception ex)
            {
                if (GenericServicesConfig.RealiseSingleExceptionMethod == null)
                {
                    throw;                                                                  //nothing to catch error
                }
                var errMsg = GenericServicesConfig.RealiseSingleExceptionMethod(ex, methodName);
                if (errMsg != null)
                {
                    status.AddSingleError(errMsg);
                }
                else
                {
                    throw; //do not understand the error so rethrow
                }
            }
            return(status);
        }
Ejemplo n.º 6
0
        public async Task TestBeforeSaveChangesMethodProvidedNoError()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <TestDbContext>();

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

                var config = new GenericServicesConfig()
                {
                    BeforeSaveChanges = FailOnBadWord
                };
                var utData  = context.SetupSingleDtoAndEntities <UniqueWithConfigDto>(config);
                var service = new CrudServicesAsync(context, utData.ConfigAndMapper);

                //ATTEMPT
                await service.CreateAndSaveAsync(new NormalEntity { MyString = "good word" });

                //VERIFY
                service.IsValid.ShouldBeTrue(service.GetAllErrors());
            }
            using (var context = new TestDbContext(options))
            {
                context.NormalEntities.Count().ShouldEqual(1);
            }
        }
        public async Task TestDirectAccessCreateWithValidationTurnedOn()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <TestDbContext>();

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

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

                //ATTEMPT
                await service.CreateAndSaveAsync(new UniqueEntity { UniqueString = "Hello" });

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

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

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

                //ATTEMPT
                service.CreateAndSave(new UniqueEntity {
                    UniqueString = "Hello"
                });

                //VERIFY
                service.GetAllErrors().ShouldEqual("Unique constraint failed");
            }
        }
Ejemplo n.º 9
0
        public void Test01ClearSqlErrorDictOk()
        {
            //SETUP

            //ATTEMPT
            GenericServicesConfig.ClearSqlErrorDict();

            //VERIFY
            GenericServicesConfig.SqlErrorDict.Count.ShouldEqual(0);
        }
Ejemplo n.º 10
0
        public void Test02DefaultSqlErrorDictOk()
        {
            //SETUP

            //ATTEMPT
            GenericServicesConfig.ClearSqlErrorDict();
            RestoreSqlErrorTextDict();

            //VERIFY
            CollectionAssert.AreEquivalent(new[] { 547, 2601 }, GenericServicesConfig.SqlErrorDict.Keys);
        }
Ejemplo n.º 11
0
        public void Test05AddNewSqlErrorDictItemOk()
        {
            //SETUP

            //ATTEMPT
            GenericServicesConfig.ClearSqlErrorDict();
            GenericServicesConfig.AddToSqlErrorDict(-1, "A test");

            //VERIFY
            GenericServicesConfig.SqlErrorDict.Count.ShouldEqual(1);
            GenericServicesConfig.SqlErrorDict[-1].ShouldEqual("A test");
        }
Ejemplo n.º 12
0
        public void TestDifferntNamesOnDefaultNameMatcher(string name, double score)
        {
            //SETUP
            var globalConfig = new GenericServicesConfig();

            //ATTEMPT
            var result = globalConfig.NameMatcher(name, typeof(int), MyIntProp);

            //VERIFY
            Math.Abs(result.Score - score).ShouldBeInRange(0, 0.001);
            _output.WriteLine(result.ToString());
        }
        public void Test21AddTwiceToErrorHandleDictOk()
        {
            //SETUP
            GenericServicesConfig.AddToSqlHandlerDict(2601, TestExceptionNoCatch);

            //ATTEMPT
            GenericServicesConfig.AddToSqlHandlerDict(2601, TestExceptionCatch, false);

            //VERIFY
            GenericServicesConfig.SqlHandlerDict.Keys.Count().ShouldEqual(1);
            GenericServicesConfig.SqlHandlerDict[2601].Method.Name.ShouldEqual("TestExceptionCatch");
        }
        public void Test20AddTwiceToErrorHandleDictBad()
        {
            //SETUP
            GenericServicesConfig.AddToSqlHandlerDict(2601, TestExceptionNoCatch);

            //ATTEMPT
            var ex =
                Assert.Throws <InvalidOperationException>(
                    () => GenericServicesConfig.AddToSqlHandlerDict(2601, TestExceptionCatch));

            //VERIFY
            ex.Message.ShouldEqual("You tried to add an exception handler for sql error 2601 but a handler called TestExceptionNoCatch was already there.");
        }
Ejemplo n.º 15
0
        public void FixtureSetup()
        {
            //This remembers the SqlErrorTextDict
            _rememberDefaultSqlErrorTextDict =
                GenericServicesConfig.SqlErrorDict.Select(x => new KeyValuePair <int, string>(x.Key, x.Value))
                .ToList();
            GenericServicesConfig.ClearSqlHandlerDict();

            using (var db = new SampleWebAppDb())
            {
                DataLayerInitialise.InitialiseThis();
                var filepath = TestFileHelpers.GetTestFileFilePath("DbContentSimple.xml");
                DataLayerInitialise.ResetDatabaseToTestData(db, filepath);
            }
        }
        public void TestSqlErrorHandlerWorksOk(int sqlErrorCode, bool shouldThrowException)
        {
            IStatusGeneric CatchUniqueError(Exception e, DbContext context)
            {
                var dbUpdateEx  = e as DbUpdateException;
                var sqliteError = dbUpdateEx?.InnerException as SqliteException;

                return(sqliteError?.SqliteErrorCode == sqlErrorCode
                    ? new StatusGenericHandler().AddError("Unique constraint failed")
                    : null);
            }

            //SETUP
            var options = SqliteInMemory.CreateOptions <TestDbContext>();

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

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

                //ATTEMPT
                try
                {
                    service.CreateAndSave(new UniqueWithConfigDto {
                        UniqueString = "Hello"
                    });
                }
                //VERIFY
                catch (Exception)
                {
                    shouldThrowException.ShouldBeTrue();
                    return;
                }

                shouldThrowException.ShouldBeFalse();
                service.GetAllErrors().ShouldEqual("Unique constraint failed");
            }
        }
        public void Test01ValidateTagCaughtByHandleDictError()
        {
            //SETUP
            GenericServicesConfig.AddToSqlHandlerDict(2601, TestExceptionCatch);
            using (var db = new SampleWebAppDb())
            {
                var existingTag = db.Tags.First();

                //ATTEMPT
                var dupTag = new Tag {
                    Name = "duplicate slug", Slug = existingTag.Slug
                };
                db.Tags.Add(dupTag);
                var status = db.SaveChangesWithChecking();

                //VERIFY
                status.IsValid.ShouldEqual(false);
                status.Errors.Count.ShouldEqual(1);
                status.Errors[0].ErrorMessage.ShouldEqual("SQL error 2601. Following class types had errors: Tag.");
            }
        }
        public void Test10ValidateTagCaughtBySqlDict()
        {
            //SETUP
            GenericServicesConfig.AddToSqlHandlerDict(2601, TestExceptionNoCatch);
            using (var db = new SampleWebAppDb())
            {
                var existingTag = db.Tags.First();

                //ATTEMPT
                var dupTag = new Tag {
                    Name = "duplicate slug", Slug = existingTag.Slug
                };
                db.Tags.Add(dupTag);
                var status = db.SaveChangesWithChecking();

                //VERIFY
                status.IsValid.ShouldEqual(false);
                status.Errors.Count.ShouldEqual(1);
                status.Errors[0].ErrorMessage.ShouldEqual("One of the properties is marked as Unique index and there is already an entry with that value.");
            }
        }
 public void FixtureSetUp()
 {
     GenericServicesConfig.ClearAutoMapperCache();
 }
 public void FixtureTearDown()
 {
     GenericServicesConfig.ClearSqlHandlerDict();
 }
 public void Setup()
 {
     GenericServicesConfig.ClearSqlHandlerDict();
 }
Ejemplo n.º 22
0
 private void RestoreSqlErrorTextDict()
 {
     _rememberDefaultSqlErrorTextDict.ForEach(x => GenericServicesConfig.AddToSqlErrorDict(x.Key, x.Value));
 }