Example #1
0
 public IHttpActionResult Get()
 {
     using (var db = new CustomerDbContext())
     {
         return(Ok(db.Customers.ToList()));
     }
 }
        public T GetRepo <T>(CustomerDbContext context)
        {
            dynamic result = null;

            if (typeof(T) == typeof(IAddressRepository))
            {
                result = new AddressRepository(context);
            }
            if (typeof(T) == typeof(IContactRepository))
            {
                result = new ContactRepository(context);
            }
            if (typeof(T) == typeof(ICustomerRepository))
            {
                result = new CustomerRepository(context);
            }
            if (typeof(T) == typeof(IAddressTypeRepository))
            {
                result = new AddressTypeRepository(context);
            }
            if (typeof(T) == typeof(IContactTypeRepository))
            {
                result = new ContactTypeRepository(context);
            }
            if (typeof(T) == typeof(ICustomerAddressRepository))
            {
                result = new CustomerAddressRepository(context);
            }
            if (typeof(T) == typeof(ICustomerContactsRepository))
            {
                result = new CustomerContactsRepository(context);
            }
            return((T)result);
        }
 public CustomerService(CustomerDbContext context, IMapper mapper, ILogger <CustomerService> logger, IValidator <CustomerDto> customerValidator)
 {
     _context           = context;
     _mapper            = mapper;
     _logger            = logger;
     _customerValidator = customerValidator;
 }
 public CustomerController(ILogger logger, ICustomerService service,
                           CustomerDbContext context)
 {
     _logger  = logger;
     _context = context;
     _service = service;
 }
Example #5
0
 public CustomersProvider(CustomerDbContext dbContext, ILogger <CustomersProvider> logger, IMapper mapper)
 {
     this.dbContext = dbContext;
     this.logger    = logger;
     this.mapper    = mapper;
     SeedData();
 }
        public CustomerRepository(CustomerDbContext dbContext, IMapper mapper)
        {
            this._dbContext = dbContext;
            this._mapper    = mapper;

            SeedData();
        }
Example #7
0
        public IActionResult getCustomerOrders(CustomerDbContext _context, string _customerName)
        {
            try
            {
                //Design an endpoint that will return a list of orders placed by a customer with the given name.
                var customerId = _context.Customers.Where(c => c.Name == _customerName).Select(c => c.IdClient);

                if (customerId == null)
                {
                    return(BadRequest("No such customer"));
                }

                var res = _context.Orders
                          .Where(d2 => d2.IdClient.Equals(customerId))
                          .ToList();

                //The result list does not have to contain information about the employee who was responsible for accepting the order or the customer`s personal data. Instead, it must consider what was included in the order (which confectionery was selected for it).
                var res2 = res.Select(o => new getCustomerOrders
                {
                    IdOrder      = o.IdOrder,
                    IdCustomer   = o.IdClient,
                    DateAccepted = o.DateAccepted,
                    DateFinished = o.DateFinished,
                    Notes        = o.Notes,
                    Confectis    = _context.Confectionery_Orders
                                   .Where(co => co.IdOrder == o.IdOrder)
                                   .Select(co => co.IdConfection).ToList()
                });
                return(Ok(res2));
            }
            catch (Exception e) { return(BadRequest(e)); }
        }
        public void AddCustomerAsync_ValidCustomer_CustomerAddedSuccessfully()
        {
            var options = new DbContextOptionsBuilder <CustomerDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                          .Options;

            using (var context = new CustomerDbContext(options))
            {
                using (var service = new Services.CustomerService.CustomerService(context))
                {
                    // First check that there are no customers.
                    var customers = service.GetCustomersByNameAsync("JA").Result;

                    customers.Count.Should().Be(0);

                    // Add single customer
                    var customer = service.AddCustomerAsync(new Customer()
                    {
                        FirstName = "jane",
                        LastName  = "dow",
                        BirthDate = "01-01-1990"
                    }).Result;

                    customers = service.GetCustomersByNameAsync("JA").Result;

                    // Now check if customer is added or not.
                    customers.Count.Should().Be(1);
                }
            }
        }
        public async Task UpdateCustomerAsync_ValidCustomer_CustomerUpdatedSuccessfully()
        {
            var options = new DbContextOptionsBuilder <CustomerDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                          .Options;

            using (var context = new CustomerDbContext(options))
            {
                using (var service = new Services.CustomerService.CustomerService(context))
                {
                    // Add single customer
                    var customer = service.AddCustomerAsync(new Customer()
                    {
                        FirstName = "jane",
                        LastName  = "dow",
                        BirthDate = "01-01-1990"
                    }).Result;

                    // Check that customer is added or not.
                    var customers = service.GetCustomersByNameAsync("JA").Result;
                    customers.Count.Should().Be(1);

                    // update customers first name
                    customer.FirstName = "updated name";

                    await service.UpdateCustomerAsync(customer.Id, customer);

                    customers = service.GetCustomersByNameAsync("dow").Result;

                    // Now check if customer first name is updated or not.
                    customers.First().FirstName.Should().Be("updated name");
                }
            }
        }
Example #10
0
 public CustomerProvider(CustomerDbContext customerDbContext, ILogger <CustomerProvider> logger, IMapper mapper)
 {
     _customerDbContext = customerDbContext;
     _logger            = logger;
     _mapper            = mapper;
     SeedData();
 }
Example #11
0
 public CustomerRepository(CustomerDbContext customerDbContext, ILogger <CustomerRepository> logger, IMapper mapper)
 {
     _customerDbContext = customerDbContext;
     _logger            = logger;
     _mapper            = mapper;
     SeedData();
 }
        public void InterceptorInConfigFileIsLoadedWhenContextOpened()
        {
            // before we've opened a context, there should be no registered instance
            Assert.IsNull(LazyLoadLoggingInterceptor.RegisteredInstance);
            using (var db = new CustomerDbContext())
            {
                // we've opened a context, so there should be an instance registered now due to the interceptor being defined in the config file
                Assert.NotNull(LazyLoadLoggingInterceptor.RegisteredInstance);
                CreateAndPopulateDatabase();
                var invoices = db.Invoices.ToList();
                Assert.NotNull(invoices);
                Assert.AreEqual(3, invoices.Count);

                // lazy load via navigation entity reference
                Assert.AreEqual(0, LazyLoadLoggingInterceptor.RegisteredInstance.LazyLoadRuntimes.Count);
                for (int i = 0; i < invoices.Count; i++)
                {
                    var queriedInvoice     = invoices.ElementAt(i);
                    var lazyLoadedCustomer = queriedInvoice.Customer;
                    Assert.AreEqual(1, lazyLoadedCustomer.CustomerId);
                    Assert.AreEqual("SomeCustomerName", lazyLoadedCustomer.Name);
                }
                Assert.AreEqual(1, LazyLoadLoggingInterceptor.RegisteredInstance.LazyLoadRuntimes.Count);
                var lazyLoadEntryForCustomerProperty = LazyLoadLoggingInterceptor.RegisteredInstance.LazyLoadRuntimes.Single();
                StringAssert.Contains("lazy load detected accessing navigation property Customer from entity Invoice", lazyLoadEntryForCustomerProperty.Key);
                Assert.AreEqual(1, lazyLoadEntryForCustomerProperty.Value.Count);
                Assert.True(lazyLoadEntryForCustomerProperty.Value.Single() >= 0); // should be a valid runtime in milliseconds
            }
        }
Example #13
0
 public CreateCustomerProcessor(
     CustomerDbContext dbContext,
     IConfirmationNumberService confirmationNumberService)
 {
     _dbContext = dbContext;
     _confirmationNumberService = confirmationNumberService;
 }
Example #14
0
        public static CustomerDbContext InitializeTestDatabase(this CustomerDbContext context)
        {
            lock (_customerContextLock)
            {
                if (!context.Customers.Any())
                {
                    context.Customers.Add(new Customer
                    {
                        ID        = 1,
                        FirstName = "John",
                        LastName  = "Doe"
                    });

                    context.Customers.Add(new Customer
                    {
                        ID        = 2,
                        FirstName = "Jane",
                        LastName  = "Doe"
                    });

                    context.Customers.Add(new Customer
                    {
                        ID        = 3,
                        FirstName = "Max",
                        LastName  = "Mustermann"
                    });

                    context.SaveChanges();
                }
                return(context);
            }
        }
Example #15
0
 public List <Customers> GetAllCustomers()
 {
     using (var _dbContext = new CustomerDbContext())
     {
         return(_dbContext.Customers.FromSqlRaw <Customers>("spCustomerGetAll").ToList());
     }
 }
        public void GetCustomersByNameAsync_InvalidSearchTerm_ReturnsEmptyCustomers()
        {
            var options = new DbContextOptionsBuilder <CustomerDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                          .Options;

            using (var context = new CustomerDbContext(options))
            {
                // Seed some data
                context.Customers.Add(
                    new Customer()
                {
                    FirstName = "jane",
                    LastName  = "dow"
                });

                context.SaveChanges();
            }

            // Use a clean instance of the context to run the test
            using (var context = new CustomerDbContext(options))
            {
                using (var service = new Services.CustomerService.CustomerService(context))
                {
                    // Act
                    var customers = service.GetCustomersByNameAsync("invalid").Result;

                    // Assert
                    customers.Should().BeNullOrEmpty();
                }
            }
        }
Example #17
0
 public Customers GetCustomerById(int id)
 {
     using (var _dbContext = new CustomerDbContext())
     {
         return(_dbContext.Customers.FromSqlRaw <Customers>($"spCustomerGetByID {id}").ToList().FirstOrDefault());
     }
 }
 public IEnumerable <Customer> GetAll()
 {
     using (var _context = new CustomerDbContext())
     {
         return(_context.Customers.ToList());
     }
 }
Example #19
0
        public IActionResult addOrder(CustomerDbContext _context, AddOrderRequest request, int _clientId)
        {
            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    var cakesNotInDatabase = 0;
                    //check if products from the request exist in the database
                    request.Confectionery.ForEach(x =>
                    {
                        if (_context.Confectioneries.Where(y => y.Name == x.Name).FirstOrDefault() == null)
                        {
                            cakesNotInDatabase++;
                        }
                    });


                    //If a product has been provided that is not in the database, stop processing the request and return the appropriate error code
                    if (cakesNotInDatabase != 0)
                    {
                        return(NotFound("One of the confectionaries doesnt exist in the database"));
                    }

                    var nextIdOrder = _context.Orders.Max(o => o.IdOrder) + 1;

                    Order o = new Order
                    {
                        IdClient     = _clientId,
                        IdOrder      = nextIdOrder,
                        DateAccepted = request.DateAccepted,
                        DateFinished = DateTime.Now,
                        Notes        = request.Notes,
                    };
                    _context.Orders.Add(o);

                    var result = request.Confectionery.Select(conf => new Confectionery_Order
                    {
                        IdConfection = _context.Confectioneries.Where(dbConf => dbConf.Name.Equals(conf.Name)).Select(dbConf => dbConf.IdConfecti).ToList().First(),
                        IdOrder      = nextIdOrder,
                        Quantity     = conf.Quantity,
                        Notes        = conf.Notes
                    });

                    foreach (Confectionery_Order co in result)
                    {
                        _context.Confectionery_Orders.Add(co);
                    }

                    _context.SaveChanges();
                    transaction.Commit();
                    return(Ok("Created a new order"));
                }

                catch (Exception e)
                {
                    transaction.Rollback();
                    return(BadRequest(e));
                }
            }
        }
 public IEnumerable <Customer> Get(int id)
 {
     using (var _context = new CustomerDbContext())
     {
         return(_context.Customers.Where(c => c.Id == id).ToList());
     }
 }
Example #21
0
 public CustomersController(ILogger <CustomersController> logger, CustomerDbContext context,
                            IHttpClientFactory httpClientFactory)
 {
     _logger           = logger;
     _context          = context;
     _taxClientFactory = httpClientFactory;
 }
Example #22
0
        public void Find_Should_Fid_The_Customer_And_Should_Return_All_Count_As_One()
        {
            var customer1 = new Domain.Customer("Caner Tosuner", "IST", DateTime.Today.AddYears(28));
            var customer2 = new Domain.Customer("Caner Tosuner", "IZM", DateTime.Today.AddYears(28));

            var options = new DbContextOptionsBuilder <CustomerDbContext>()
                          .UseInMemoryDatabase("customer_db")
                          .Options;

            using (var context = new CustomerDbContext(options))
            {
                var repository = new CustomerRepository(context);
                repository.Save(customer1);
                repository.Save(customer2);
                context.SaveChanges();
            }

            using (var context = new CustomerDbContext(options))
            {
                var repository = new CustomerRepository(context);
                var result     = repository.Find(c => c.CityCode == customer1.CityCode);
                result.Should().NotBeNull();
                result.Count().Should().Be(1);
            }
        }
Example #23
0
        public void EditCustomerAsync_UpdatesCustomer()
        {
            SetupCustomers(2);

            using (_customerDbContext = new CustomerDbContext(_options))
            {
                _customerController = new CustomerController(_customerDbContext);

                var updatedCustomer = new CustomerRequest
                {
                    FirstName   = "Bar",
                    LastName    = "Bash",
                    DateOfBirth = DateTime.Now.Date
                };

                var result = _customerController.EditCustomerAsync(1, updatedCustomer);
                var value  = result.Result.Value;

                Assert.Equal(1, value.Id);
                Assert.Equal(updatedCustomer.FirstName, value.FirstName);
                Assert.Equal(updatedCustomer.LastName, value.LastName);
                Assert.Equal(updatedCustomer.DateOfBirth, value.DateOfBirth);
                Assert.IsAssignableFrom <Customer>(value);
            }
        }
Example #24
0
        public void Delete_Should_Delete_The_Customer_And_Should_Return_All_Count_As_One()
        {
            var customer1 = new Domain.Customer("Caner Tosuner", "IST", DateTime.Today.AddYears(28));
            var customer2 = new Domain.Customer("Caner Tosuner", "IST", DateTime.Today.AddYears(28));

            var options = new DbContextOptionsBuilder <CustomerDbContext>()
                          .UseInMemoryDatabase("customer_db")
                          .Options;

            using (var context = new CustomerDbContext(options))
            {
                var repository = new CustomerRepository(context);
                repository.Save(customer1);
                repository.Save(customer2);
                context.SaveChanges();
            }

            using (var context = new CustomerDbContext(options))
            {
                var repository = new CustomerRepository(context);
                repository.Delete(customer1.Id);
                context.SaveChanges();
            }

            using (var context = new CustomerDbContext(options))
            {
                var repository = new CustomerRepository(context);
                repository.All().Count().Should().Be(1);
            }
        }
        public ActionResult Edit(int?ID)
        {
            ViewBag.StatusList = GetStatusList();         //Not sure how else to do this, getting an error when posting this
                                                          //didnt want to duplicate code so moved to a method but doesnt feel
                                                          //like a good solution.
                                                          //(error)there is no status list object, need to look at tempdata maybe?

            using (var context = new CustomerDbContext()) //uses the db context to add the customer sub to the db
            {
                if (ID == null)
                {
                    var result = new HttpNotFoundResult("No User ID associated with this customer");
                    return(result);
                }

                var customerToUpdate = context.Customers.Find(ID);
                TryUpdateModel(customerToUpdate);
                if (ModelState.IsValid)
                {
                    try
                    {
                        context.SaveChanges();
                        return(View("Index", context.Customers.ToList()));
                    }
                    catch (Exception)
                    {
                        ModelState.AddModelError("", "Unable to edit the customer");
                    }
                }
                return(View(customerToUpdate));
            }
        }
Example #26
0
        public void Update_Should_Update_The_Customer()
        {
            var customer = new Domain.Customer("Caner Tosuner", "IST", DateTime.Today.AddYears(28));

            var options = new DbContextOptionsBuilder <CustomerDbContext>()
                          .UseInMemoryDatabase("customer_db")
                          .Options;

            using (var context = new CustomerDbContext(options))
            {
                var repository = new CustomerRepository(context);
                repository.Save(customer);
                context.SaveChanges();
            }

            customer.SetFields("Caner T", "IZM", customer.BirthDate);

            using (var context = new CustomerDbContext(options))
            {
                var repository = new CustomerRepository(context);
                repository.Update(customer);
                context.SaveChanges();
            }

            using (var context = new CustomerDbContext(options))
            {
                var repository = new CustomerRepository(context);
                var result     = repository.Get(customer.Id);

                result.Should().NotBe(null);
                result.FullName.Should().Be(customer.FullName);
                result.CityCode.Should().Be(customer.CityCode);
                result.BirthDate.Should().Be(customer.BirthDate);
            }
        }
Example #27
0
 public CustomerRepository()
 {
     if (dbContext == null)
     {
         dbContext = new CustomerDbContext();
     }
 }
Example #28
0
 public void DeleteCustomer(int id)
 {
     using (var _dbContext = new CustomerDbContext())
     {
         _dbContext.Database.ExecuteSqlRaw($"spCustomerDelete {id}");
     }
 }
        public ActionResult LoadData()
        {
            try
            {
                //Creating instance of DatabaseContext class
                using (CustomerDbContext _context = new CustomerDbContext())
                {
                    var expenseData = (from e in _context.Expenses
                                       join p in _context.Projects on e.ProjectId equals p.ProjectId
                                       select new
                    {
                        ExpenseId = e.ExpenseId,
                        Name = e.Name,
                        ProjectName = p.Name,
                        Amout = e.Amout
                    }).ToList();


                    return(Json(new { data = expenseData }, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public IActionResult List()
        {
            CustomerDbContext db        = new CustomerDbContext();
            List <Customer>   customers = db.Customers.Where(c => c.isDeleted == false).ToList();

            return(View(customers));
        }