public async Task SeedAsync()
        {
            _context.Database.EnsureCreated();
            StoreUser user = await _userManager.FindByEmailAsync("*****@*****.**");

            if (user == null)
            {
                user = new StoreUser
                {
                    FirstName = "elyes",
                    LastName  = "ben zina",
                    UserName  = "******",
                    Email     = "*****@*****.**"
                };
                var result = await _userManager.CreateAsync(user, "P@ssw0rd!");

                if (result != IdentityResult.Success)
                {
                    throw new InvalidOperationException("Could not create new user in seeder");
                }
            }
            if (!_context.Products.Any())
            {
                var filePath = Path.Combine(_hosting.ContentRootPath, "Data/art.json");
                var json     = File.ReadAllText(filePath);
                var products = JsonConvert.DeserializeObject <IEnumerable <Product> >(json);
                _context.Products.AddRange(products);
                var order = _context.Orders.FirstOrDefault(o => o.Id == 1);
                if (order != null)
                {
                    order.User = user;
                    new OrderItem
                    {
                        Product   = products.First(),
                        Quantity  = 5,
                        UnitPrice = products.First().Price
                    };
                }
                _context.SaveChanges();
            }
        }
Exemple #2
0
        private void _associateProductAndUserWithDefaultOrder(Product product, StoreUser user)
        {
            var order = _context.Orders.Where(pOrder => pOrder.Id == 1).FirstOrDefault();

            if (order == null)
            {
                return;
            }

            order.User = user;

            order.Items = new List <OrderItem>()
            {
                new OrderItem()
                {
                    Product   = product,
                    Quantity  = 5,
                    UnitPrice = product.Price
                }
            };
        }
Exemple #3
0
        public async Task SeedAsync()
        {
            _context.Database.EnsureCreated();

            var user = await _userManager.FindByEmailAsync("*****@*****.**");

            if (user == null)
            {
                user = new StoreUser()
                {
                    FirstName = "Pedro",
                    LastName  = "Test",
                    Email     = "*****@*****.**",
                    UserName  = "******"
                };

                var saveResult = await _userManager.CreateAsync(user, "P@ssw0rd!");

                if (saveResult != IdentityResult.Success)
                {
                    throw new InvalidOperationException("Cannot create user in seeder!");
                }
            }

            if (!_context.Products.Any())
            {
                _logger.LogWarning("No products detected, seeding products");
                var seedDataPath = Path.Combine(_host.ContentRootPath, "Data/art.json");
                var rawData      = File.ReadAllText(seedDataPath);
                var products     = JsonConvert.DeserializeObject <IEnumerable <Product> >(rawData);
                _context.Products.AddRange(products);

                var order = _context.Orders.Where(o => o.Id == 1).FirstOrDefault();
                // Originally the course had the seed order created on DutchContext
                // This led to the order not being inserted for whatever reason
                // this code is a workaround
                if (order == null)
                {
                    _logger.LogWarning("No orders detected, seeding orders");
                    order = new Order()
                    {
                        OrderDate   = DateTime.UtcNow,
                        OrderNumber = "12345",
                        User        = user
                    };

                    order.Items = new List <OrderItem>()
                    {
                        new OrderItem()
                        {
                            Quantity  = 5,
                            UnitPrice = products.First().Price,
                            Product   = products.First()
                        }
                    };
                    _context.Orders.Add(order);
                }

                var changes = _context.SaveChanges();
                _logger.LogWarning($"{changes} have been saved to database");
            }
        }
Exemple #4
0
        public async Task Seed()
        {
            // make sure the datbase actually created!
            _ctx.Database.EnsureCreated();

            //because the following is async, change the signature of the invoker to be
            // async task too
            var user = await _userManager.FindByEmailAsync("*****@*****.**");

            if (user == null)
            {
                //there are several properties you could set, however we only set the following
                user = new StoreUser()
                {
                    FirstName = "Eakan",
                    LastName  = "Gopalakrishnan",
                    UserName  = "******",
                    Email     = "*****@*****.**"
                };
                //while creating a user you can also set the password
                var result = await _userManager.CreateAsync(user, "P@$$w0RD!");

                if (result != IdentityResult.Success)
                {
                    throw new InvalidOperationException("Failed to create default user!");
                }
            }

            if (!_ctx.Products.Any())
            {
                // need to load a lot of data and not want to manually add new product objects
                // one by one.
                // we need a path to the file first. we could pass a hardcoded string
                // this will work in visual studio but not runtime. so we can inject ihostingenvironment
                var filepath = Path.Combine(_hosting.ContentRootPath, "Data/art.json");
                var json     = File.ReadAllText(filepath);

                var products = JsonConvert.DeserializeObject <IEnumerable <Product> >(json);

                _ctx.Products.AddRange(products);

                // add previously created user to the order
                var order = new Order()
                {
                    OrderDate   = DateTime.Now,
                    OrderNumber = "12345",
                    User        = user,
                    Items       = new List <OrderItem>()
                    {
                        new OrderItem()
                        {
                            Product   = products.First(),
                            Quantity  = 5,
                            UnitPrice = products.First().Price
                        }
                    }
                };
                _ctx.Orders.Add(order);
                _ctx.SaveChanges();
            }
        }
Exemple #5
0
        public async Task SeedAsync()
        {
            //if (_hosting.IsDevelopment())
            //{
            //    _ctx.Database.EnsureDeleted(); //kill the database??  Here we goooooooo!
            //}

            _ctx.Database.EnsureCreated(); //Check that the database actually exists

            StoreUser user = await _manager.FindByEmailAsync("*****@*****.**");

            if (user == null)
            {
                user = new StoreUser()
                {
                    FirstName = "Jason",
                    LastName  = "Thomson",
                    Email     = "*****@*****.**",
                    UserName  = "******"
                };

                var result = await _manager.CreateAsync(user, "P@ssw0rd!");

                if (result != IdentityResult.Success)
                {
                    throw new InvalidOperationException("Unable to create user in seeder.");
                }
            }

            if (!_ctx.Products.Any()) //Make sure there are in fact existing products
            {
                //Create sample data
                var filepath = Path.Combine(_hosting.ContentRootPath, "Data/art.json");
                var json     = File.ReadAllText(filepath);
                var products = JsonConvert.DeserializeObject <IEnumerable <Product> >(json);

                _ctx.Products.AddRange(products);

                // add orders
                var order = _ctx.Orders.Where(o => o.Id == 1).FirstOrDefault();
                if (order != null)
                {
                    order.User  = user;
                    order.Items = new List <OrderItem>()
                    {
                        new OrderItem()
                        {
                            Product   = products.First(),
                            Quantity  = 5,
                            UnitPrice = products.First().Price
                        }
                    };
                }
                else
                {
                    _ctx.Add(new Order()
                    {
                        OrderDate   = DateTime.UtcNow,
                        OrderNumber = "TestJace",
                        Items       = new List <OrderItem>()
                        {
                            new OrderItem()
                            {
                                Product   = products.First(),
                                Quantity  = 5,
                                UnitPrice = products.First().Price
                            }
                        }
                    });
                }

                _ctx.SaveChanges();
            }
        }
        public async Task SeedAsync()
        {
            _dbContext.Database.EnsureDeleted();
            _dbContext.Database.EnsureCreated();

            StoreUser user = await _userManager.FindByEmailAsync("*****@*****.**");

            if (user == null)
            {
                user = new StoreUser()
                {
                    FirstName = "Kiril",
                    LastName  = "Stanoev",
                    Email     = "*****@*****.**",
                    UserName  = "******"
                };

                var result = await _userManager.CreateAsync(user, "1234");

                if (result != IdentityResult.Success)
                {
                    throw new InvalidOperationException("Failed to create user");
                }
            }


            _dbContext.Database.OpenConnection();
            try
            {
                _dbContext.Database.ExecuteSqlCommand("DELETE FROM dbo.Products");
                _dbContext.Database.ExecuteSqlCommand("DELETE FROM dbo.Orders");
                _dbContext.SaveChanges();
            }
            finally
            {
                _dbContext.Database.CloseConnection();
            }

            if (!_dbContext.Products.Any())
            {
                var filePath = Path.Combine(_host.ContentRootPath, "Data\\sampleProductsData.json");
                var json     = File.ReadAllText(filePath);
                var products = JsonConvert.DeserializeObject <IEnumerable <Product> >(json);
                _dbContext.Products.AddRange(products);
                _dbContext.Database.OpenConnection();
                try
                {
                    _dbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Products ON");
                    _dbContext.SaveChanges();
                    _dbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Products OFF");
                }
                finally
                {
                    _dbContext.Database.CloseConnection();
                }

                var order = new Order()
                {
                    Id = 1
                };
                order.User      = user;
                order.OrderDate = DateTime.Now;
                order.Items     = new List <OrderItem>()
                {
                    new OrderItem()
                    {
                        Product = products.First(),
                        Price   = new decimal(3.14),
                        Order   = order
                    }
                };
                _dbContext.Orders.Add(order);

                _dbContext.Database.OpenConnection();
                try
                {
                    _dbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Orders ON");
                    _dbContext.SaveChanges();
                    _dbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Orders OFF");
                }
                finally
                {
                    _dbContext.Database.CloseConnection();
                }

                _dbContext.SaveChanges();
            }
        }
Exemple #7
0
        public async Task SeedAsync()
        {
            _ctx.Database.EnsureCreated();

            StoreUser user = await this._userManager.FindByEmailAsync("*****@*****.**");

            if (user == null)
            {
                user = new StoreUser()
                {
                    FirstName = "zhenying",
                    LastName  = "zhu",
                    Email     = "*****@*****.**",
                    UserName  = "******"
                };

                var result = await this._userManager.CreateAsync(user, "P@ssw0rd!");

                if (result != IdentityResult.Success)
                {
                    throw new InvalidOperationException("Could not create a new user in seeder.");
                }
            }

            if (!_ctx.Orders.Any())
            {
                // It should created in DutchContext.OnModelCreating.
                Order testOrder = new Order()
                {
                    OrderDate   = DateTime.Now,
                    OrderNumber = "#1"
                };
                _ctx.Orders.Add(testOrder);

                _ctx.SaveChanges();
            }

            if (!_ctx.Products.Any())
            {
                var filepath = Path.Combine(this._hosting.ContentRootPath, "Data/art.json");
                var json     = File.ReadAllText(filepath);
                var products = JsonConvert.DeserializeObject <IEnumerable <Product> >(json);

                //_ctx.Products.AddRange(products);
                // zhenying: trying to figure out which data exceed size.
                // turns out the Title was set to 50 as the length. Changed it to 250.
                foreach (var product in products)
                {
                    _ctx.Products.Add(product);
                    try
                    {
                        _ctx.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        continue;
                    }
                }

                _ctx.SaveChanges();
            }

            var order = _ctx.Orders.Where(o => o.Id == 1).FirstOrDefault();

            if (order != null && (order.Items == null || !order.Items.Any()))
            {
                order.User  = user;
                order.Items = new List <OrderItem>()
                {
                    new OrderItem()
                    {
                        Product   = _ctx.Products.First(),
                        Quantity  = 5,
                        UnitPrice = _ctx.Products.First().Price
                    }
                };

                _ctx.SaveChanges();
            }
        }