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

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

                var controller = new ToDoController();
                var utData     = context.SetupSingleDtoAndEntities <ChangeDifficultyDto>(_genericServiceConfig);
                var service    = new CrudServices(context, utData.ConfigAndMapper);

                //ATTEMPT
                var response = controller.Delete(2, service);

                //VERIFY
                response.GetStatusCode().ShouldEqual(CreateResponse.OkStatusCode);
                var rStatus = response.CopyToStatus();
                rStatus.IsValid.ShouldBeTrue(rStatus.GetAllErrors());
                rStatus.Message.ShouldEqual("Successfully deleted a Todo Item");
                context.TodoItems.Count().ShouldEqual(5);
            }
        }
        public void TestPutNameOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <ExampleDbContext>();

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

                var controller = new ToDoController();
                var utData     = context.SetupSingleDtoAndEntities <ChangeNameDto>(_genericServiceConfig);
                var service    = new CrudServices(context, utData.ConfigAndMapper);

                //ATTEMPT
                var dto = new ChangeNameDto()
                {
                    Id   = 2,
                    Name = "Test",
                };
                var response = controller.Name(dto, service);

                //VERIFY
                response.GetStatusCode().ShouldEqual(CreateResponse.OkStatusCode);
                var rStatus = response.CopyToStatus();
                rStatus.IsValid.ShouldBeTrue(rStatus.GetAllErrors());
                rStatus.Message.ShouldEqual("Successfully updated the Todo Item");
            }
        }
        public void TestPutDifficultyValidationError()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <ExampleDbContext>();

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

                var controller = new ToDoController();
                var utData     = context.SetupSingleDtoAndEntities <ChangeDifficultyDto>(_genericServiceConfig);
                var service    = new CrudServices(context, utData.ConfigAndMapper);

                //ATTEMPT
                var dto = new ChangeDifficultyDto()
                {
                    Id         = 1,
                    Difficulty = 99,
                };
                var response = controller.Difficulty(dto, service);

                //VERIFY
                response.GetStatusCode().ShouldEqual(CreateResponse.ErrorsStatusCode);
                var rStatus = response.CopyToStatus();
                rStatus.IsValid.ShouldBeFalse();
                rStatus.GetAllErrors().ShouldEqual("The field Difficulty must be between 1 and 5.");
            }
        }
Example #4
0
        public void ReferencingANonIncludedEntityWillLazyLoadedViaASecondQuery()
        {
            using (ExampleDbContext dbContext = new ExampleDbContext())
            {
                dbContext.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

                Person person = dbContext.Persons.First(p => p.Name == PERSON_JANE);

                /*
                 * SELECT TOP (1)
                 *  [Extent1].[Id] AS [Id],
                 *  [Extent1].[Name] AS [Name]
                 *  FROM [dbo].[Person] AS [Extent1]
                 *  WHERE N'Jane' = [Extent1].[Name]
                 * */

                Assert.That(person.Pets.First(), Is.Not.Null);

                //the below query isn't emitted until the call to person.Pets.First() as it is lazy loaded

                /*
                 * SELECT
                 *  [Extent1].[Id] AS [Id],
                 *  [Extent1].[Name] AS [Name],
                 *  [Extent1].[OwningPersonId] AS [OwningPersonId]
                 *  FROM [dbo].[Pet] AS [Extent1]
                 *  WHERE [Extent1].[OwningPersonId] = @EntityKeyValue1
                 * */
            }
        }
        public void TestCreateTodoOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <ExampleDbContext>();

            using (var context = new ExampleDbContext(options))
            {
                context.Database.EnsureCreated();
                context.SeedDatabase();
                var controller = new ToDoController();

                var noCachingConfig = new GenericBizRunnerConfig {
                    TurnOffCaching = true
                };
                var utData      = new NonDiBizSetup(noCachingConfig);
                var bizInstance = new CreateTodoBizLogic(context);
                var service     = new ActionService <ICreateTodoBizLogic>(context, bizInstance, utData.WrappedConfig);

                //ATTEMPT
                var dto = new CreateTodoDto()
                {
                    Name       = "Test",
                    Difficulty = 3,
                };
                var response = controller.Post(dto, service);

                //VERIFY
                response.GetStatusCode().ShouldEqual(201);
                var rStatus = response.CheckCreateResponse("GetSingleTodo", new { id = 7 }, context.TodoItems.Find(7));
                rStatus.IsValid.ShouldBeTrue(rStatus.GetAllErrors());
                rStatus.Message.ShouldEqual("Success");
            }
        }
 public IEnumerable<Person> GetSomePeople()
 {
     using (var ctx = new ExampleDbContext())
     {
         return ctx.People.AsNoTracking().Take(30).ToList();
     }
 }
Example #7
0
        public void ReferencingANonIncludedRelatedEntityThatWasAlreadyLoadedOnThisDbContextWillReturnANonNullValueBecauseItIsAlreadyCachedUpEvenWithLazyLoadingDisabled()
        {
            using (ExampleDbContext dbContext = new ExampleDbContext())
            {
                dbContext.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
                dbContext.Configuration.LazyLoadingEnabled = false;

                //fetch all pets so they are cached up on the dbContext already
                List <Pet> pets = dbContext.Pets.ToList();

                /*
                 * SELECT
                 *  [Extent1].[Id] AS [Id],
                 *  [Extent1].[Name] AS [Name],
                 *  [Extent1].[OwningPersonId] AS [OwningPersonId]
                 *  FROM [dbo].[Pet] AS [Extent1]
                 * */

                Person person = dbContext.Persons.First(p => p.Name == PERSON_JANE);

                /*
                 * SELECT TOP (1)
                 *  [Extent1].[Id] AS [Id],
                 *  [Extent1].[Name] AS [Name]
                 *  FROM [dbo].[Person] AS [Extent1]
                 *  WHERE N'Jane' = [Extent1].[Name]
                 * */

                //no query is emitted because the Pets property is already fully loaded as it was already cached on the DbContext
                Assert.That(person.Pets, Is.Not.Null);
            }
        }
 public IEnumerable<Message> GetMessages()
 {
     using (var ctx = new ExampleDbContext())
     {
         return ctx.Messages.Take(30).ToList();
     }
 }
Example #9
0
 public GetUserClaimsQueryHandlerTests(ITestOutputHelper output)
 {
     _output              = output;
     _dbHelper            = new DbHelper <ExampleDbContext>().RunMigrations();
     _handlerDbContext    = _dbHelper.GetDbContext();
     _httpContextAccessor = new TestHttpContextAccessor();
     _handler             = new GetUserClaimsQueryHandler <ExampleDbContext>(_handlerDbContext, _httpContextAccessor);
 }
        public HomeController(ExampleDbContext dbContext)
        {
            _dbContext = dbContext;

            var dbinit = new DbInitializer(dbContext);

            dbinit.Initialize();
        }
Example #11
0
 public CheckUserHasPrivilegeQueryHandlerTests(ITestOutputHelper output)
 {
     _output              = output;
     _dbHelper            = new DbHelper <ExampleDbContext>().RunMigrations();
     _handlerDbContext    = _dbHelper.GetDbContext();
     _httpContextAccessor = new TestHttpContextAccessor();
     _handler             = new CheckUserHasPrivilegeQueryHandler <ExampleDbContext>(_handlerDbContext, _httpContextAccessor);
 }
 protected void ReadAgain(Guid id)
 {
     using (var dbContext = new ExampleDbContext(_dbContextOptions))
     {
         var t = dbContext.Find <EfcThing>(id);
         Assert.That(t.Id, Is.EqualTo(id));
     }
 }
Example #13
0
        public TokenWrapper(Token originalToken, DeviantArtApp app, ExampleDbContext context)
        {
            _originalToken = originalToken;
            _context       = context;

            CurrentToken = originalToken;
            App          = app;
        }
Example #14
0
 public SaveUserCommandTests(ITestOutputHelper output)
 {
     _output           = output;
     _dbHelper         = new DbHelper <ExampleDbContext>().RunMigrations();
     _handlerDbContext = _dbHelper.GetDbContext();
     _handler          = new SaveUserCommandHandler <ExampleDbContext>(_handlerDbContext);
     _validator        = new SaveUserCommandValidator <ExampleDbContext>(_handlerDbContext);
 }
Example #15
0
        public static void SeedTwoTaxRates(this ExampleDbContext context)
        {
            var rateNow   = new TaxRate(DateTime.Today, 4);
            var rate2Days = new TaxRate(DateTime.Today.AddDays(2), 9);

            context.AddRange(rateNow, rate2Days);
            context.SaveChanges();
        }
Example #16
0
 public RemoveSystemRolePrivilegeCommandTests(ITestOutputHelper output)
 {
     _output           = output;
     _dbHelper         = new DbHelper <ExampleDbContext>().RunMigrations();
     _handlerDbContext = _dbHelper.GetDbContext();
     _handler          = new RemoveSystemRolePrivilegeCommandHandler <ExampleDbContext>(_handlerDbContext);
     _validator        = new RemoveSystemRolePrivilegeCommandValidator <ExampleDbContext>(_handlerDbContext);
 }
        public void Setup()
        {
            var configuration = new ExampleInstaller(NullLoggerFactory.Instance).Config;

            using (var dbContext = new ExampleDbContext(configuration.Options))
            {
                dbContext.Database.EnsureCreated();
            }
        }
        public IActionResult GetData([FromForm] FilterRequest model)
        {
            var context = new ExampleDbContext();

            context.Database.EnsureCreated();
            var result = context.Customers.AsQueryable().Load(model);

            return(Json(result));
        }
Example #19
0
 public DataSource.User Get(int userId)
 {
     using (var db = new ExampleDbContext())
     {
         return(db.User
                .Include(x => x.UserType)
                .FirstOrDefault(x => x.UserId == userId));
     }
 }
Example #20
0
 public static void Main(string[] args)
 {
     using (var db = new ExampleDbContext())
     {
         var xx = db.User
                  .Include(x => x.UserType)
                  .FirstOrDefault(x => x.UserId == 1);
     }
 }
Example #21
0
        public ActionResult OnPost()
        {
            StringBuilder resultSB = new StringBuilder();

            try
            {
                ResultMessage = "";

                resultSB.Append("Into Post <br/>");

                using (var dbCtx = new ExampleDbContext()
                {
                    ConnectionString = "User ID = waleedpg; Password = AbcXyz123; Server = localhost; Port = 5432; Database = turkexample2; "
                })
                //    + "Integrated Security = true; Pooling = true;""))
                {
                    resultSB.Append("Into using <br/>");

                    var klnclr = dbCtx.Kullanıcılar;

                    if (klnclr != null && klnclr.Any())
                    {
                        resultSB.Append("Got users <br/>");

                        Kullanıcılar = klnclr.ToList();
                    }
                    else
                    {
                        resultSB.Append("There are no users!! <br/>");
                    }

                    //var prsns = dbCtx.persons;

                    //if (prsns != null && prsns.Any())
                    //{
                    //    foreach (var p in prsns)
                    //        personsListBox.Items.Add($"{p.name} {p.birthdate.ToString("yyyy-MM-dd")} {p.email}");
                    //}
                }

                resultSB.Append("Out of Post <br/>");

                ResultMessage = resultSB.ToString();

                return(Page());
            }
            catch (Exception ex)
            {
                resultSB.Append(ex.ToString());

                ResultMessage = resultSB.ToString();

                return(Page());
            }
        }
Example #22
0
 public SampleOrderModel(IHostingEnvironment hostingEnvironment,
                         IUploadFileService uploadFileService,
                         IExamplesRepository examplesRepository,
                         ExampleDbContext context)
 {
     _hostingEnvironment = hostingEnvironment;
     _uploadFileService  = uploadFileService;
     _context            = context;
     _exampleRepository  = examplesRepository;
     Orders = new List <OrderViewModel>();
 }
 public static void Seed(ExampleDbContext ctx)
 {
     if (!ctx.People.Any())
     {
         LoadPeopleData(ctx.Database.Connection.ConnectionString);
     }
     else
     {
         LogMsg("People records have already been added to the database.");
     }
 }
Example #24
0
        public static List <ProductStock> SeedExampleProductStock(this ExampleDbContext context)
        {
            var prodStocks = new List <ProductStock>
            {
                new ProductStock("Product1", 5),
                new ProductStock("Product2", 10),
                new ProductStock("Product3", 20),
            };

            context.AddRange(prodStocks);
            context.SaveChanges();
            return(prodStocks);
        }
Example #25
0
        public AddClassificationCommandValidator(ExampleDbContext db)
        {
            RuleFor(e => e.Code)
            .NotEmpty()
            .Must(e => !db.Classifications.Any(c => c.Code == e)).WithLocalizedStringMessage(typeof(Core.Resources.Validation), "CodeAlreadyExists")
            ;

            RuleFor(e => e.DescEng)
            .MaximumLength(250);

            RuleFor(e => e.DescFre)
            .MaximumLength(255);
        }
Example #26
0
 public static async Task <List <PersonEntity> > GetPeopleEf()
 {
     try
     {
         using (var db = new ExampleDbContext())
         {
             return(await db.People.ToListAsync());
         }
     }
     catch (Exception e)
     {
         return(new List <PersonEntity>());
     }
 }
Example #27
0
        public InviteNewUserAccountCommandTests()
        {
            _dbHelper         = new DbHelper <ExampleDbContext>().RunMigrations();
            _handlerDbContext = _dbHelper.GetDbContext();

            _emailSender         = new TestEmailSender();
            _httpContextAccessor = new TestHttpContextAccessor();
            _testUserService     = new TestUserService();

            var authEmailSender = new AuthEmailSender(_httpContextAccessor, _emailSender, GetIdentityProviderConfiguration(), GetApplicationConfiguration());

            _handler   = new InviteNewUserAccountCommandHandler <ExampleDbContext>(_handlerDbContext, authEmailSender, _testUserService);
            _validator = new InviteNewUserAccountCommandValidator <ExampleDbContext>(_handlerDbContext);
        }
Example #28
0
        public CustomerApiController(ExampleDbContext context,
                                     ICustomerRepository _repository,
                                     IUnitOfWork unitOfWork)
        {
            this._repository = _repository;
            this.unitOfWork  = unitOfWork;
            this._context    = context;

            // if (_context.Customers.Count() == 0)
            // {
            //     _context.Customers.Add(new Customer { Name = "Mustafa", Surname = "Alkan", Age = 31 });
            //     _context.SaveChanges();
            // }
        }
 public Person GetPerson(int personId)
 {
     using (var ctx = new ExampleDbContext())
     {
         return
             ctx
                 .People
                 .Include(p => p.EmailAddresses)
                 .Include(p => p.PostalAddresses)
                 .Include(p => p.PhoneNumbers)
                 .AsNoTracking()
                 .SingleOrDefault(p => p.PersonId == personId);
     }
 }
        protected virtual Guid SaveIt()
        {
            using (var dbContext = new ExampleDbContext(_dbContextOptions))
            {
                var newThing = new EfcThing
                {
                    Value = 45.0
                };
                dbContext.Add(newThing);
                dbContext.SaveChanges();

                return(newThing.Id);
            }
        }
        protected override void Seed(ExampleDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
Example #32
0
        public static void Register(HttpConfiguration config)
        {
            var dbContext = new ExampleDbContext();
            var container = new UnityContainer();

            container.RegisterType<IRdfWriter, RdfXmlWriter>(new InjectionConstructor());

            container.RegisterType<ISelpConfiguration, InMemoryConfiguration>();
            var efConstructorParameter = new InjectionConstructor(dbContext, container.Resolve<ISelpConfiguration>());

            container.RegisterType<IUserRepository, UserRepository>(efConstructorParameter);
            container.RegisterType<IRegionRepository, RegionRepository>(efConstructorParameter);
            container.RegisterType<IPolicyRepository, PolicyRepository>(efConstructorParameter);
            container.RegisterType<IPartyRepository, PartyRepository>(efConstructorParameter);
            config.DependencyResolver = new UnityResolver(container);
        }
        public void TestSeedDatabaseOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <ExampleDbContext>();

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

                //ATTEMPT
                context.SeedDatabase();

                //VERIFY
                context.TodoItems.Count().ShouldEqual(6);
            }
        }
Example #34
0
        public void TestCreateDatabaseSeedTaxAndStock()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <ExampleDbContext>();

            using (var context = new ExampleDbContext(options))
            {
                //ATTEMPT
                context.Database.EnsureCreated();
                context.SeedTaxAndStock();

                //VERIFY
                context.TaxRates.Count().ShouldEqual(2);
                context.ProductStocks.Count().ShouldEqual(3);
            }
        }
Example #35
0
        static void Main(string[] args)
        {
            var configBuilder = new ConfigurationBuilder();

            configBuilder.AddJsonFile("appsettings.json");

            var configuration = configBuilder.Build();

            using var sqlServerDbContext = new ExampleDbContext(configuration, DatabaseType.SqlServer);
            using var postgresDbContext  = new ExampleDbContext(configuration, DatabaseType.PostgreSql);
            var personToAdd = new Person("Tom", "Brady", new DateTime(1980, 10, 10));

            sqlServerDbContext.Person.Add(personToAdd);
            postgresDbContext.Person.Add(personToAdd);
            sqlServerDbContext.SaveChanges();
            postgresDbContext.SaveChanges();
        }
 public void UpdatePerson(Person person)
 {
     using (var ctx = new ExampleDbContext())
     {
         ctx.People.Attach(person);
         ctx.Entry(person).State = EntityState.Modified;
         ctx.SaveChanges();
     }
 }
 public DatabaseSeed(ExampleDbContext dbContext)
 {
     _dbContext = dbContext;
 }
 public void CreatePerson(Person person)
 {
     using (var ctx = new ExampleDbContext())
     {
         ctx.People.Add(person);
         ctx.SaveChanges();
     }
 }
        public void DeletePerson(int personId)
        {
            using (var ctx = new ExampleDbContext())
            {
                var person = ctx.People.SingleOrDefault(p => p.PersonId == personId);
                if (person == null)
                {
                    throw new ObjectNotFoundException("Invalid person id.");
                }

                ctx.People.Remove(person);
                ctx.SaveChanges();
            }
        }
        public PersonResponse GetPeople(PeopleRequest request)
        {
            request.Validate();

            using (var ctx = new ExampleDbContext())
            {
                IQueryable<Person> query;

                query = ctx.People.AsNoTracking();

                var orderBy = (request.OrderBy ?? "").ToLower();
                switch (orderBy)
                {
                    default:
                        query =
                            request.Descending
                                ? query.OrderByDescending(p => p.LastName).ThenByDescending(p => p.FirstName)
                                : query.OrderBy(p => p.LastName).ThenBy(p => p.FirstName);
                        break;
                    case "firstname":
                        query =
                            request.Descending
                                ? query.OrderByDescending(p => p.FirstName).ThenByDescending(p => p.LastName)
                                : query.OrderBy(p => p.FirstName).ThenBy(p => p.LastName);
                        break;
                    case "middlename":
                        query =
                            request.Descending
                                ? query.OrderByDescending(p => p.MiddleName).ThenByDescending(p => p.FirstName).ThenByDescending(p => p.LastName)
                                : query.OrderBy(p => p.MiddleName).ThenBy(p => p.FirstName).ThenBy(p => p.LastName);
                        break;
                    case "suffix":
                        query =
                            request.Descending
                                ? query.OrderByDescending(p => p.Suffix).ThenByDescending(p => p.LastName).ThenByDescending(p => p.FirstName)
                                : query.OrderBy(p => p.Suffix).ThenBy(p => p.LastName).ThenBy(p => p.FirstName);
                        break;
                    case "title":
                        query =
                            request.Descending
                                ? query.OrderByDescending(p => p.Title).ThenByDescending(p => p.LastName).ThenByDescending(p => p.FirstName)
                                : query.OrderBy(p => p.Title).ThenBy(p => p.LastName).ThenBy(p => p.FirstName);
                        break;
                }

                var results = 
                    query
                        .Skip((request.PageIndex - 1) * request.PageSize)
                        .Take(request.PageSize)
                        .GroupBy(r => new { Total = query.Count() })
                        .ToList();

                if (results.Count == 0)
                {
                    return
                        new PersonResponse
                        {
                            Total = 0,
                            Page = 0,
                            Records = 0,
                            Rows = Enumerable.Empty<Person>().ToList()
                        };
                }

                int totalRecordCount = results[0].Key.Total;
                return new PersonResponse
                    {
                        Total = totalRecordCount / request.PageSize,
                        Page = request.PageIndex,
                        Records = totalRecordCount,
                        Rows = results[0].ToList()
                    };
            }
        }