Пример #1
0
 public static bool DeleteUser(int id)
 {
     try
     {
         var user = new User()
         {
             Id = id
         };
         using (var dbCtx = new MSDbContext())
         {
             dbCtx.Users.Remove(user);
             int result = dbCtx.SaveChanges();
             if (result == 1)
             {
                 return(true);
             }
             else
             {
                 throw new Exception();
             }
         }
     }
     catch (Exception e)
     {
         var ex = new DeleteFromDataBaseException(ExceptionMessage.DeleteFromUsersException, e);
         Logger.Log.Error(ex.Message, ex);
         throw ex;
     }
 }
Пример #2
0
 public HomeController(MSDbContext context, ILogger <HomeController> logger,
                       IProductRepository productRepository)
 {
     _context           = context;
     _logger            = logger;
     _productRepository = productRepository;
 }
Пример #3
0
 public static int InsertActivation(NewActivationReq newActivation)
 {
     try
     {
         var activation = new Activation()
         {
             UserId         = newActivation.UserId,
             ActivationCode = newActivation.ActicationCode.ToString(),
             IsActive       = true
         };
         using (var dbCtx = new MSDbContext())
         {
             dbCtx.Activations.Add(activation);
             int result = dbCtx.SaveChanges();
             if (result == 1)
             {
                 return(activation.Id);
             }
             else
             {
                 throw new Exception();
             }
         }
     }
     catch (Exception e)
     {
         var ex = new InsertIntoDataBaseException(ExceptionMessage.InsertIntoActivationsException, e);
         Logger.Log.Error(ex.Message, ex);
         throw ex;
     }
 }
        public async void GetsAllProducts()
        {
            //Arrange
            var options = InMemoryDb("GetsAllProducts");

            //Act
            using (var context = new MSDbContext(options))
            {
                var product = new Product
                {
                    Id    = 6,
                    Price = 150.55M,
                };
                context.Add(product);
                product = new Product
                {
                    Id    = 7,
                    Price = 150.55M,
                };
                context.Add(product);
                context.SaveChanges();
            }
            //Assert
            using (var context = new MSDbContext(options))
            {
                var productRepo = new ProductRepository(context);
                var products    = await productRepo.GetAllAsync();

                Assert.Equal(6, products.Count());
            }
        }
Пример #5
0
 public static int InsertUser(NewUserReq newUser)
 {
     try
     {
         var user = new User()
         {
             IsActive = true,
             Name     = newUser.Name,
             Tel      = newUser.Tel
         };
         using (var dbCtx = new MSDbContext())
         {
             dbCtx.Users.Add(user);
             int result = dbCtx.SaveChanges();
             if (result == 1)
             {
                 return(user.Id);
             }
             else
             {
                 throw new Exception();
             }
         }
     }
     catch (Exception e)
     {
         var ex = new InsertIntoDataBaseException(ExceptionMessage.InsertIntoUsersException, e);
         Logger.Log.Error(ex.Message, ex);
         throw ex;
     }
 }
        public void AddsProductToDbTest()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <MSDbContext>()
                          .UseInMemoryDatabase(databaseName: "AddsProductToDbTest")
                          .Options;

            //Act
            using (var db = new MSDbContext(options))
            {
                Product sitar = new Product
                {
                    Id    = 17,
                    Name  = "sitar",
                    Price = 100M
                };

                db.Add(sitar);
                db.SaveChanges();
            }

            //Assert
            using (var context = new MSDbContext(options))
            {
                Assert.Equal(1, context.Products.Count());

                var product1 = context.Products.Where(p => p.Id == 17).FirstOrDefault();
                Assert.Equal(17, product1.Id);
                Assert.Equal("sitar", product1.Name);
            }
        }
        public async Task DeletesProductFromDb()
        {
            //Arrange - create an object to configure your inmemory DB.
            var options = new DbContextOptionsBuilder <MSDbContext>()
                          .UseInMemoryDatabase(databaseName: "DeletesProductFromDb")
                          .Options;


            //Act - send in the configure object to the DbContext constructor to be used in configuring the DbContext
            using (var db = new MSDbContext(options))
            {
                Product product = new Product
                {
                    Id   = 26,
                    Name = "drum",
                };
                db.Add(product);
                await db.SaveChangesAsync();

                db.Remove(product);
                await db.SaveChangesAsync();
            }

            //Assert
            using (var context = new MSDbContext(options))
            {
                Assert.Equal(0, context.Products.Count());
            }
        }
        public void CustomerSearchByUserByLastName()
        {
            // Arrange
            var options = new DbContextOptionsBuilder <MSDbContext>()
                          .UseInMemoryDatabase(databaseName: "CustomerByName")
                          .Options;
            Customer cust = new Customer
            {
                FirstName = "Test User",
                LastName  = "Test Last"
            };

            string lastName = "Test";

            //Act
            using (var context = new MSDbContext(options))
            {
                context.Add(cust);
                context.SaveChanges();

                var result = context.Customers
                             .Where(c => c.LastName.Contains(lastName))
                             .AsNoTracking().FirstOrDefault();

                //Assert
                Assert.Equal(cust.LastName, result.LastName);
            }
        }
Пример #9
0
 public static bool ValidateToken(string phoneNumber, string token)
 {
     try
     {
         using (var dbCtx = new MSDbContext())
         {
             var userToken = (from t in dbCtx.Tokens
                              join u in dbCtx.Users on t.UserId equals u.Id
                              where t.TokenStr == token &&
                              u.Tel == phoneNumber &&
                              t.IsActive
                              select new { t, u }).FirstOrDefault();
             if (userToken == null)
             {
                 return(false);
             }
             var now  = DateTime.Now;
             var diff = now - userToken.t.LastUsageTime;
             if (diff.Days > 30)
             {
                 return(false);
             }
             userToken.t.LastUsageTime = now;
             dbCtx.SaveChanges();
             return(true);
         }
     }
     catch (Exception e)
     {
         var ex = new SelectFromDataBaseException(ExceptionMessage.ValidatingToken, e);
         Logger.Log.Error(ex.Message, ex);
         throw ex;
     }
 }
        public void ShoppingCartHasItems()
        {
            // Arrange
            var options = new DbContextOptionsBuilder <MSDbContext>()
                          .UseInMemoryDatabase(databaseName: "CustomerByName")
                          .Options;
            ShoppingCartItem cartItem = new ShoppingCartItem
            {
                ShoppingCartId = "1",
                customerEmail  = "*****@*****.**",
                Quantity       = 2,
                StoreId        = "5"
            };


            //Act
            using (var context = new MSDbContext(options))
            {
                context.Add(cartItem);
                context.SaveChanges();

                var result = context.ShoppingCartItems
                             .Where(c => c.customerEmail.Contains(cartItem.customerEmail))
                             .AsNoTracking().FirstOrDefault();

                //Assert
                Assert.Equal(cartItem.customerEmail, result.customerEmail);
            }
        }
Пример #11
0
 public ProductsController(MSDbContext context, IProductRepository productRepository,
                           ICustomerRepository customerRepository)
 {
     _context            = context;
     _productRepository  = productRepository;
     _customerRepository = customerRepository;
 }
        public async Task GetsAllLocations()
        {
            //Arrange
            var options = InMemoryDb("GetsAllLocations");

            //Act
            using (var context = new MSDbContext(options))
            {
                var store = new Store
                {
                    Name = "Florida"
                };
                context.Add(store);
                store = new Store
                {
                    Name = "Texas"
                };
                context.Add(store);
                store = new Store
                {
                    Name = "Washington"
                };
                context.Add(store);
                await context.SaveChangesAsync();
            }
            //Assert
            using (var context = new MSDbContext(options))
            {
                var stores = context.Stores.Select(x => x);
                //var stores = await storeRepo.();

                Assert.Equal(4, stores.Count());
            }
        }
Пример #13
0
 public static int InsertToken(NewTokenReq newToken)
 {
     try
     {
         var token = new Token()
         {
             IsActive      = true,
             UserId        = newToken.UserId,
             TokenStr      = newToken.TokenStr,
             LastUsageTime = newToken.TokenTime
         };
         using (var dbCtx = new MSDbContext())
         {
             dbCtx.Tokens.Add(token);
             int result = dbCtx.SaveChanges();
             if (result == 1)
             {
                 return(token.Id);
             }
             else
             {
                 throw new Exception();
             }
         }
     }
     catch (Exception e)
     {
         var ex = new InsertIntoDataBaseException(ExceptionMessage.InsertIntoTokensException, e);
         Logger.Log.Error(ex.Message, ex);
         throw ex;
     }
 }
Пример #14
0
        public async Task AddsCustomerToDb()
        {
            //Arrange - create an object to configure your inmemory DB.
            var options = new DbContextOptionsBuilder <MSDbContext>()
                          .UseInMemoryDatabase(databaseName: "AddsCustomerToDb")
                          .Options;


            //Act - send in the configure object to the DbContext constructor to be used in configuring the DbContext
            using (var db = new MSDbContext(options))
            {
                CustomerAddress customerAddress = new CustomerAddress {
                    Id = 1, Street = "8286 Clay Ave.", City = "Spokane", State = "WA", Zip = "11111"
                };
                Customer customer = new Customer {
                    Id = 6, FirstName = "Maribeth", LastName = "Fontenot", Email = "*****@*****.**", PhoneNo = "1234112233", Password = "******", UserTypeId = 2, CustomerAddress = customerAddress
                };
                db.Add(customer);
                db.SaveChanges();
            }

            //Assert
            using (var context = new MSDbContext(options))
            {
                Assert.Equal(1, context.Customers.Count());
                var customer1 = await context.Customers.Where(x => x.FirstName == "Maribeth")
                                .AsNoTracking().FirstOrDefaultAsync();

                var customer1Address = await context.Customers.
                                       Include(c => c.CustomerAddress).AsNoTracking().FirstOrDefaultAsync();

                Assert.Equal("Maribeth", customer1.FirstName);
                Assert.Equal("11111", customer1Address.CustomerAddress.Zip);
            }
        }
Пример #15
0
        public async Task FindCustomerById_ShouldReturnCustomer_WhenCustomerExits()
        {
            // Arrange
            var options = new DbContextOptionsBuilder <MSDbContext>()
                          .UseInMemoryDatabase(databaseName: "AddsCustomerToDb")
                          .Options;

            using (var db = new MSDbContext(options))
            {
                Customer customer = new Customer
                {
                    Id         = 6,
                    FirstName  = "Maribeth",
                    LastName   = "Fontenot",
                    Email      = "*****@*****.**",
                    PhoneNo    = "1234112233",
                    Password   = "******",
                    UserTypeId = 2
                };

                var result = await db.Customers
                             .Include(c => c.CustomerAddress)
                             .AsNoTracking()
                             .Where(c => c.Id == customer.Id).FirstOrDefaultAsync();

                // Assert
                Assert.Equal(6, customer.Id);
            }
        }
Пример #16
0
        public async Task DeletesCustomerFromDb()
        {
            //Arrange - create an object to configure your inmemory DB.
            var options = new DbContextOptionsBuilder <MSDbContext>()
                          .UseInMemoryDatabase(databaseName: "DeletesCustomerToDb")
                          .Options;


            //Act - send in the configure object to the DbContext constructor to be used in configuring the DbContext
            using (var db = new MSDbContext(options))
            {
                CustomerAddress customerAddress = new CustomerAddress {
                    Id = 1, Street = "8286 Clay Ave.", City = "Spokane", State = "WA", Zip = "11111"
                };
                Customer customer = new Customer {
                    Id = 6, FirstName = "Maribeth", LastName = "Fontenot", Email = "*****@*****.**", PhoneNo = "1234112233", Password = "******", UserTypeId = 2, CustomerAddress = customerAddress
                };
                db.Add(customer);
                await db.SaveChangesAsync();

                db.Remove(customer);
                await db.SaveChangesAsync();
            }

            //Assert
            using (var context = new MSDbContext(options))
            {
                Assert.Equal(0, context.Customers.Count());
            }
        }
        public async Task DeletesOrderFromDb()
        {
            //Arrange - create an object to configure your inmemory DB.
            var options = new DbContextOptionsBuilder <MSDbContext>()
                          .UseInMemoryDatabase(databaseName: "DeletesOrderFromDb")
                          .Options;


            //Act - send in the configure object to the DbContext constructor to be used in configuring the DbContext
            using (var db = new MSDbContext(options))
            {
                Order order = new Order
                {
                    Id      = 43,
                    StoreId = 4
                };
                db.Add(order);
                await db.SaveChangesAsync();

                db.Remove(order);
                await db.SaveChangesAsync();
            }

            //Assert
            using (var context = new MSDbContext(options))
            {
                Assert.Equal(0, context.Orders.Count());
            }
        }
        public void AddsStoreToDbTest()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <MSDbContext>()
                          .UseInMemoryDatabase(databaseName: "AddsStoreToDbTest")
                          .Options;

            //Act
            using (var db = new MSDbContext(options))
            {
                Store location = new Store
                {
                    Name = "Spokane"
                };

                db.Add(location);
                db.SaveChanges();
            }

            //Assert
            using (var context = new MSDbContext(options))
            {
                Assert.Equal(1, context.Stores.Count());

                var store2 = context.Stores.Where(s => s.Id == 1).FirstOrDefault();
                Assert.Equal(1, store2.Id);
                Assert.Equal("Spokane", store2.Name);
            }
        }
Пример #19
0
        public Repository(MSDbContext dbContext, IUnitOfWork unitOfWork)
        {
            if (dbContext == null)
            {
                throw new Exception("repository could not work without dbContext");
            }

            (unitOfWork as UnitOfWork)?.RegisterDbContext(dbContext);
            Container = dbContext;
        }
        public async void GetsAllOrdersForCustomer()
        {
            //Arrange
            var options = InMemoryDb("GetsCustomersOrders");

            //Act
            using (var context = new MSDbContext(options))
            {
                var customer = new Customer
                {
                    Id        = 4,
                    FirstName = "Conan",
                    LastName  = "perse",
                    Email     = "*****@*****.**"
                };
                context.Add(customer);
                context.SaveChanges();
                CreateTwoproducts(context);

                var store = new Store
                {
                    Id   = 7,
                    Name = "SomeLocation"
                };
                context.Add(store);
                context.SaveChanges();

                var order = new Order
                {
                    CustomerId = 2,
                    OrderDate  = DateTime.Now,
                    StoreId    = 3,
                };
                context.Add(order);
                order = new Order
                {
                    CustomerId = 6,
                    OrderDate  = DateTime.Now,
                    StoreId    = 5,
                };
                context.Add(order);
                context.SaveChanges();
            }
            //Assert
            using (var context = new MSDbContext(options))
            {
                IHttpContextAccessor contextAccessor = new HttpContextAccessor();
                var shoppingCartRepo = new ShoppingCart(context);
                var orderRepo        = new OrderService(context, shoppingCartRepo, contextAccessor);
                var orders           = await orderRepo.FindAsync(o => o.CustomerId == 1);

                Assert.Empty(orders);
            }
        }
        private void CreateOneCustomer(MSDbContext context)
        {
            var customer = new Customer
            {
                Id        = 1,
                FirstName = "Conan",
                LastName  = "perse",
                Email     = "*****@*****.**"
            };

            context.Add(customer);
            context.SaveChanges();
        }
Пример #22
0
 public Repository(MSDbContext dbContext, IUnitOfWork unitOfWork)
 {
     _UnitOfWork = unitOfWork as UnitOfWork;
     if (dbContext == null)
     {
         throw new Exception("repository could not work without dbContext");
     }
     // dbContext.Configuration.AutoDetectChangesEnabled = false;
     if (_UnitOfWork != null)
     {
         _UnitOfWork.RegisterDbContext(dbContext);
     }
     _Container = dbContext;
 }
Пример #23
0
        public static ServiceProviderSpecificResp SelectServiceProviderById(int id)
        {
            try
            {
                using (var dbCtx = new MSDbContext())
                {
                    var server = (from s in dbCtx.Servers
                                  join c in dbCtx.Categories on s.CategoryId equals c.Id
                                  join sp in dbCtx.ServerPhotos on s.Id equals sp.ServerId into ssp
                                  from sp in ssp.DefaultIfEmpty()
                                  where s.IsActive && c.IsActive && s.Id == id &&
                                  (sp.IsPrimary || sp == null)
                                  select new { s, c, sp.Photo }).FirstOrDefault();
                    if (server == null)
                    {
                        return(null);
                    }
                    var photos = (from p in dbCtx.ServerPhotos
                                  where p.ServerId == id
                                  select p).ToList();
                    List <string> photoBase64List = new List <string>();
                    foreach (var photo in photos)
                    {
                        string temp = Convert.ToBase64String(photo.Photo);
                        photoBase64List.Add(temp);
                    }

                    ServiceProviderSpecificResp serviceProvider = new ServiceProviderSpecificResp()
                    {
                        Id           = server.s.Id,
                        Name         = server.s.Name,
                        Address      = server.s.Address,
                        CategoryName = server.c.Name,
                        CategoryId   = server.c.Id,
                        Tel          = server.s.Tel,
                        PrimaryPhoto = server.Photo != null?Convert.ToBase64String(server.Photo) : null,
                                           PhotoList = photoBase64List
                    };
                    return(serviceProvider);
                }
            }
            catch (Exception e)
            {
                var ex = new SelectFromDataBaseException(ExceptionMessage.SelectFromCategoriesServerIdException, e);
                Logger.Log.Error(ex.Message, ex);
                throw ex;
            }
        }
        private void CreateTwoproducts(MSDbContext context)
        {
            var product = new Product
            {
                Id    = 1,
                Price = 150.55M,
            };

            context.Add(product);
            product = new Product
            {
                Id    = 2,
                Price = 150.55M,
            };
            context.Add(product);
            context.SaveChanges();
        }
Пример #25
0
        public static int InsertServerInfo(BE.Entities.Request.ServerInfoReq serverInfo)
        {
            try
            {
                var server = new Entities.Server()
                {
                    Name       = serverInfo.Name,
                    Address    = serverInfo.Address,
                    Tel        = serverInfo.Tel,
                    IsActive   = true,
                    CategoryId = serverInfo.CategoryId
                };
                using (var dbCtx = new MSDbContext())
                {
                    dbCtx.Servers.Add(server);
                    int result = dbCtx.SaveChanges();

                    if (result == 1)
                    {
                        foreach (var serverPhoto in serverInfo.Photos)
                        {
                            byte[] photoByte      = Convert.FromBase64String(serverPhoto);
                            var    serverPhotoEnt = new Entities.ServerPhoto()
                            {
                                Photo    = photoByte,
                                ServerId = server.Id
                            };
                            dbCtx.ServerPhotos.Add(serverPhotoEnt);
                            dbCtx.SaveChanges();
                        }
                        return(server.Id);
                    }
                    else
                    {
                        throw new Exception();
                    }
                }
            }
            catch (Exception e)
            {
                var ex = new InsertIntoDataBaseException(ExceptionMessage.InsertIntoServersException, e);
                Logger.Log.Error(ex.Message, ex);
                throw ex;
            }
        }
Пример #26
0
 public static List <Category> SelectAllCategories()
 {
     try
     {
         using (var dbCtx = new MSDbContext())
         {
             var categories = (from t in dbCtx.Categories
                               select t).ToList();
             return(categories);
         }
     }
     catch (Exception e)
     {
         var ex = new SelectFromDataBaseException(ExceptionMessage.SelectFromCategoriesException, e);
         Logger.Log.Error(ex.Message, ex);
         throw ex;
     }
 }
Пример #27
0
 public static bool DeleteServiceProviderLike(ServiceProviderLikeReq likeReq)
 {
     try
     {
         using (var dbCtx = new MSDbContext())
         {
             dbCtx.ServiceProviderLike.RemoveRange(
                 dbCtx.ServiceProviderLike.Where(x => x.User.Tel == likeReq.UserMobileNumber && x.ServerId == likeReq.ServerId));
             dbCtx.SaveChanges();
             return(true);
         }
     }
     catch (Exception e)
     {
         var ex = new InsertIntoDataBaseException(ExceptionMessage.DeleteServiceProviderLikeException, e);
         Logger.Log.Error(ex.Message, ex);
         throw ex;
     }
 }
Пример #28
0
 public static User SelectUserByTel(string tel)
 {
     try
     {
         using (var dbCtx = new MSDbContext())
         {
             var user = (from u in dbCtx.Users
                         where u.Tel == tel
                         select u).FirstOrDefault();
             return(user);
         }
     }
     catch (Exception e)
     {
         var ex = new SelectFromDataBaseException(ExceptionMessage.SelectFromUsersByTelException, e);
         Logger.Log.Error(ex.Message, ex);
         throw ex;
     }
 }
Пример #29
0
 public static List <ServiceProviderGeneralInfoResp> SelectLikedServicesByPageIndex(string userMobileNumber, int pageIndex)
 {
     try
     {
         using (var dbCtx = new MSDbContext())
         {
             List <ServiceProviderGeneralInfoResp> spList = new List <ServiceProviderGeneralInfoResp>();
             var user    = UserAccounts.SelectUserByTel(userMobileNumber);
             var servers = (from s in dbCtx.Servers
                            join likes in dbCtx.ServiceProviderLike on s.Id equals likes.ServerId
                            join c in dbCtx.Categories on s.CategoryId equals c.Id
                            join sp in dbCtx.ServerPhotos on s.Id equals sp.ServerId into ssp
                            from sp in ssp.DefaultIfEmpty()
                            where s.IsActive && c.IsActive && likes.UserId == user.Id &&
                            (sp.IsPrimary || sp == null)
                            orderby s.Id descending
                            select new { s, c, sp.Photo }).Skip(ItemsPerPage * pageIndex).Take(ItemsPerPage).ToList();
             foreach (var server in servers)
             {
                 var temp = new ServiceProviderGeneralInfoResp()
                 {
                     Id           = server.s.Id,
                     Name         = server.s.Name,
                     CategoryId   = server.c.Id,
                     CategoryName = server.c.Name,
                     PrimaryPhoto = server.Photo != null?Convert.ToBase64String(server.Photo) : null
                 };
                 spList.Add(temp);
             }
             return(spList);
         }
     }
     catch (Exception e)
     {
         var ex = new SelectFromDataBaseException(ExceptionMessage.SelectFromCategoriesIdServersException, e);
         Logger.Log.Error(ex.Message, ex);
         throw ex;
     }
 }
Пример #30
0
 public static bool ExistActivationByUser(ActivationCodeReq activationCode)
 {
     try
     {
         using (var dbCtx = new MSDbContext())
         {
             var userActiovation = (from a in dbCtx.Activations
                                    join u in dbCtx.Users on a.UserId equals u.Id
                                    where a.ActivationCode == activationCode.Code &&
                                    u.Tel == activationCode.Tel &&
                                    a.IsActive
                                    select new { a, u }).FirstOrDefault();
             return(userActiovation != null);
         }
     }
     catch (Exception e)
     {
         var ex = new SelectFromDataBaseException(ExceptionMessage.ExistActivationByUser, e);
         Logger.Log.Error(ex.Message, ex);
         throw ex;
     }
 }