コード例 #1
0
        public Domain.Models.Customer GetOrderHistoryByCustomer(int id)
        {
            // This method is called because we need the information on the whole catalog
            // Since the catalog is small I went with this implementation.
            // If it was much large I would only fill the Domain with the relevant books
            FillBookLibrary();

            // Attempt to find the customer
            Entities.CustomerEntity dbCustomer = _context.Customers
                                                 .Include(l => l.Location)
                                                 .Include(o => o.Orders)
                                                 .ThenInclude(ol => ol.Orderlines)
                                                 .FirstOrDefault(c => c.Id == id);

            // If the customer was not found then let the user know
            if (dbCustomer == null)
            {
                return(null);
            }

            // if one was found then map it to a usable object
            Domain.Models.Customer m_customer = MapperCustomer.MapCustomerWithOrders(dbCustomer);

            return(m_customer);
        }
コード例 #2
0
        private string GenerateUnsignName(Domain.Models.Customer CustomerInfo, List <CustomerContact> listCustomerContacts)
        {
            var unsignName = CustomerInfo.FullName.Trim().StripVietnameseChars().ToUpper();

            return(listCustomerContacts.Aggregate(unsignName,
                                                  (current, CustomerContact) => current + $" {CustomerContact.ContactValue.Trim().StripVietnameseChars().ToUpper()}"));
        }
コード例 #3
0
        private static bool ValidateUpdatePhoneNumberRequest(DomainCustomer customer, JsonPatchDocument <DomainCustomer> patchDoc)
        {
            var phoneNumberPath      = DomainCustomer.PropNameToPatchPath[nameof(DomainCustomer.Phone.PhoneNumber)];
            var phoneNumberRequest   = patchDoc.Operations.SingleOrDefault(o => o.path.Equals(phoneNumberPath));
            var isPhoneNumberRequest = phoneNumberRequest != null;

            if (!isPhoneNumberRequest)
            {
                return(false);
            }

            var requestedPhoneNumber = phoneNumberRequest?.value.ToString();

            Validate.PhoneNumberFormat(requestedPhoneNumber);

            if (string.IsNullOrEmpty(requestedPhoneNumber))
            {
                throw new InvalidRequestException("Phone number cannot be null or empty.");
            }

            if (customer.Phone?.PhoneNumber == requestedPhoneNumber)
            {
                patchDoc.Operations.Remove(phoneNumberRequest);
                return(false);
            }

            return(true);
        }
コード例 #4
0
        public void Update(Domain.Models.Customer entity)
        {
            Customer entityToUpdate = this.context.Customers.First(x => x.CustomerID == entity.CustomerID);

            this.mapper.Map(entity, entityToUpdate);
            this.context.SaveChanges();
        }
コード例 #5
0
 public Domain.Models.Customer Update(Domain.Models.Customer updated)
 {
     Entities.Customer mappedCust = mapper.Map(updated, context, true);
     context.SaveChanges();
     //context.ChangeTracker.Clear();
     return(mapper.Map(mappedCust));
 }
コード例 #6
0
        public void GetById()
        {
            // Arrange
            var customer = new Domain.Models.Customer(new Guid(), "Alan", "*****@*****.**", new DateTime());

            var customerRepositoryMock = new Mock <ICustomerRepository>();

            customerRepositoryMock.Setup(x => x.GetById(customer.Id))
            .Returns(customer);
            var mapperMock = new Mock <IMapper>();

            mapperMock.Setup(x => x.Map <CustomerViewModel>(customer)).Returns(new CustomerViewModel
            {
                Id        = customer.Id,
                Name      = customer.Name,
                Email     = customer.Email,
                BirthDate = customer.BirthDate,
            });

            // Act
            var sut    = new CustomerAppService(mapperMock.Object, customerRepositoryMock.Object, null, null);
            var result = sut.GetById(customer.Id);

            // Assert
            Assert.Equal(result.Id, customer.Id);
            Assert.Equal(result.Name, customer.Name);
            Assert.Equal(result.Email, customer.Email);
            Assert.Equal(result.BirthDate, customer.BirthDate);
        }
コード例 #7
0
        /// <summary>
        /// This method tries to update an entity in the database through setting EntityFramework Core's Entry property to EntityState.Modified. If the update fails an exception is thrown. If the update succeeds then the customer parameter object passed in is saved to the database.
        /// </summary>
        /// <param name="customer"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <bool> ModifyStateAsync(Domain.Models.Customer customer, int id)
        {
            var mappedCustomer = Mapper.MapCustomer(customer);

            /*_context.Entry(customer).State = EntityState.Modified;*/
            _context.Entry(mappedCustomer).State = EntityState.Modified;

            try
            {
                await SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CustomerExists(id))
                {
                    return(false);
                    // customer not found
                }
                else
                {
                    throw;
                }
            }
            return(true);
            // it worked, so return true
        }
コード例 #8
0
        public void Map(IMapperConfigurationExpression cfg)
        {
            cfg.CreateMap <UpdateCustomer, Domain.Models.Customer>()
            .ConstructUsing(c =>
            {
                var customer =
                    new Domain.Models.Customer(
                        c.FirstName,
                        c.LastName,
                        c.Email,
                        c.BirthDate,
                        c.Id
                        );
                return(customer);
            })
            .IgnoreAllPropertiesWithAnInaccessibleSetter();

            cfg.CreateMap <Domain.Models.Customer, UpdateCustomer>()
            .ForMember(d => d.Email, o => o.MapFrom(s => s.EmailAddress))
            .ForMember(d => d.Number, o => o.MapFrom(s => s.Address.Number))
            .ForMember(d => d.Street, o => o.MapFrom(s => s.Address.Street))
            .ForMember(d => d.ZipCode, o => o.MapFrom(s => s.Address.ZipCode))
            .ForMember(d => d.Street, o => o.MapFrom(s => s.Address.Street))
            .ForMember(d => d.Number, o => o.MapFrom(s => s.Address.Number))
            .ForMember(d => d.City, o => o.MapFrom(s => s.Address.City))
            .ForMember(d => d.ZipCode, o => o.MapFrom(s => s.Address.ZipCode));
        }
コード例 #9
0
        public async Task <CustomerDto> Handle(CreateCustomerCommand request, CancellationToken cancellationToken)
        {
            if (await _customerRepository.EmailExistAsync(request.Email))
            {
                string msg = $"This email {nameof(request.Email)} is already existed!";
                _logger.LogError(msg);

                throw new BadRequestException(msg);
            }

            var customer = new Domain.Models.Customer(request.Name, request.Email, request.Address, request.Age, request.PhoneNumber);

            _customerRepository.Add(customer);

            if (await _customerRepository.SaveChangesAsync() == 0)
            {
                throw new Exceptions.ApplicationException("Couldn't save data");
            }

            await _mediator.Publish(new Domain.Events.CustomerCreatedEvent(customer.Id), cancellationToken);

            var customerDto = _customerDxos.MapCustomerDto(customer);

            return(customerDto);
        }
コード例 #10
0
 public Entities.Customer Map(Domain.Models.Customer Customer)
 {
     return(new Entities.Customer
     {
         ID = Customer.ID,
         Name = Customer.Name
     });
 }
コード例 #11
0
        public int Insert(Domain.Models.Customer entity)
        {
            Customer entityToInsert = this.context.Customers.Create();

            this.mapper.Map(entity, entityToInsert);
            this.context.Customers.Add(entityToInsert);
            this.context.SaveChanges();
            return(entityToInsert.CustomerID);
        }
コード例 #12
0
 public void Update(Domain.Models.Customer existing, Domain.Models.Customer updated)
 {
     PizzaBox.Storing.Entities.Customer customer = context.Customers.ToList().Find(customer => customer.Name.Equals(existing.Name));
     if (customer is not null)
     {
         customer.Name = updated.Name;
         context.SaveChanges();
     }
 }
コード例 #13
0
 private static Entities.Customer MapToEntity(
     Domain.Models.Customer domainCustomer)
 {
     return(new Entities.Customer
     {
         CustomerId = domainCustomer.CustomerId,
         Age = domainCustomer.Age
     });
 }
コード例 #14
0
 public void Remove(Domain.Models.Customer t)
 {
     PizzaBox.Storing.Entities.Customer customer = context.Customers.ToList().Find(customer => customer.Name.Equals(t.Name));
     if (customer is not null)
     {
         context.Customers.Remove(customer);
         context.SaveChanges();
     }
 }
コード例 #15
0
 ///-------------------------------------------------------------------------------------------------------------------
 ///-------------------------------------------------------------------------------------------------------------------
 ///-------------------------------------------------------------------------------------------------------------------
 ///-------------------------------------------------------------------------------------------------------------------
 ///-------------------------------------------------------------------------------------------------------------------
 public static Models.Address MapAddress(Domain.Models.Customer address)
 {
     return(new Models.Address
     {
         Street = address.street,
         City = address.city,
         State = address.state,
         Zip = address.zip
     });
 }
コード例 #16
0
 /// <summary>
 /// Turn a model customer with their location into a entity customer
 /// </summary>
 /// <param name="customer"></param>
 /// <returns></returns>
 public static Entities.CustomerEntity MapCustomerWithLocation(Domain.Models.Customer customer)
 {
     return(new Entities.CustomerEntity
     {
         FirstName = customer.FirstName,
         LastName = customer.LastName,
         Id = customer.ID,
         Location = MapperLocation.Map(customer.MyStoreLocation)
     });
 }
コード例 #17
0
 /// <summary>
 /// This turns a customer Model into a customer entity, by assigning each relavent property
 /// to a column in the customer table
 /// </summary>
 /// <param name="customer">The customer model.</param>
 /// <returns></returns>
 public static Entities.CustomerEntity Map(Domain.Models.Customer customer)
 {
     return(new Entities.CustomerEntity
     {
         FirstName = customer.FirstName,
         LastName = customer.LastName,
         Id = customer.ID,
         LocationId = customer.MyStoreLocation.ID
     });
 }
コード例 #18
0
        public async Task InsertCustomerAsync(
            Domain.Models.Customer customer,
            CancellationToken cancellationToken = default)
        {
            var entity = MapToEntity(customer);

            _customerDbContext.Customers.Add(entity);

            await _customerDbContext
            .SaveChangesAsync(cancellationToken);
        }
コード例 #19
0
        public async Task <string> GetCustomerId(string tenantId, string fullName, string phone, string email, string address)
        {
            var unsignName = fullName.Trim().StripVietnameseChars().ToUpper();
            var customerId = _customerRepository.GetCustomerId(tenantId, unsignName, phone, email);

            if (!string.IsNullOrEmpty(customerId))
            {
                return(customerId);
            }

            customerId = Guid.NewGuid().ToString();
            var customer = new Domain.Models.Customer
            {
                Id                 = customerId,
                TenantId           = tenantId,
                FullName           = fullName,
                UnsignName         = fullName.Trim().StripVietnameseChars().ToUpper(),
                Birthday           = DateTime.Now,
                Gender             = 2,
                CustomerResourceId = "-1",
                IdCardNumber       = string.Empty,
                JobId              = -1,
                NationalId         = -1,
                NationalName       = string.Empty,
                EthnicId           = -1,
                EthnicName         = string.Empty,
                ReligionId         = -1,
                ReligionName       = string.Empty,
                ProvinceId         = -1,
                DistrictId         = -1,
                DistrictName       = string.Empty,
                Address            = address
            };

            var resultInsert = await _customerRepository.Insert(customer);

            var customerContacts = new List <CustomerContact>();

            var item1 = new CustomerContact {
                Id = Guid.NewGuid().ToString(), CustomerId = customerId, ContactType = ContactType.Email, ContactValue = email
            };
            var item2 = new CustomerContact {
                Id = Guid.NewGuid().ToString(), CustomerId = customerId, ContactType = ContactType.MobilePhone, ContactValue = phone
            };

            customerContacts.Add(item1);
            customerContacts.Add(item2);

            await _customerContactRepository.Inserts(customerContacts);


            return(customerId);
        }
コード例 #20
0
        /// <summary>
        /// Wraps a call to EntityFramework Core Add. The call is made with a mapped entity (DataAccess.Models.Customer) instead of the domain model passed as a parameter. The DataAccess.Model is used to communicate with EF Core.
        ///
        /// EF Core Add:
        /// Finds an entity with the given primary key values. If an entity with the given primary key values is being tracked by the context, then it is returned immediately without making a request to the database. Otherwise, a query is made to the database for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found, then null is returned.
        /// </summary>
        /// <param name="entity"></param>
        /// <returns>Domain.Models.Customer</returns>
        public void Add(Domain.Models.Customer entity)
        {
            var mappedAddress = Mapper.MapAddress(entity);

            _context.Set <Address>().Add(mappedAddress);
            _context.SaveChanges();
            _context.Entry(mappedAddress).Reload();
            var mappedEntity = Mapper.MapCustomer(entity);

            mappedEntity.Address = mappedAddress.AddressId;
            _context.Set <Customer>().Add(mappedEntity);
        }
コード例 #21
0
 public static Customer1 Map(Domain.Models.Customer Cx)
 {
     return(new Customer1()
     {
         Id = Cx.Id,
         Fname = Cx.Fname,
         Lname = Cx.Lname,
         Email = Cx.Email,
         UserPass = Cx.UserPass,
         Phone = Cx.Phone
     });
 }
コード例 #22
0
        public Entities.Customer Map(Domain.Models.Customer model, Entities.AnimalsDbContext context)
        {
            var dbCustomer = context.Customers.FirstOrDefault(c => c.Name.Equals(model.Name));

            if (dbCustomer is not null)
            {
                return(dbCustomer);
            }

            Entities.Customer customer = new Entities.Customer();
            customer.Name = model.Name;
            return(customer);
        }
コード例 #23
0
 public Customer(DomainCustomer domainCustomer)
 {
     Id        = domainCustomer.Id;
     FirstName = domainCustomer.FirstName;
     LastName  = domainCustomer.LastName;
     Email     = domainCustomer.Email;
     Phone     = new Phone
     {
         PhoneNumber = domainCustomer.Phone.PhoneNumber,
         IsVerified  = domainCustomer.Phone.IsVerified,
     };
     CreatedDateTime = domainCustomer.CreatedDateTime;
 }
コード例 #24
0
 public static Models.Customer MapCustomer(Domain.Models.Customer customer)
 {
     return(new Models.Customer
     {
         CustomerId = customer.CustomerId,
         Email = customer.Email,
         Phone = customer.Phone,
         Policies = customer.Policies,
         Name = customer.Name
                //AddressNavigation = MapAddress(customer.AddressNavigation)
                //PoliciesNavigation = MapPolicies(customer.PoliciesNavigation),
                //Invoice = customer.Invoice.Select(MapInvoice).ToList(),
                //PlanReviews = customer.PlanReviews.Select(MapPlanReviews).ToList()
     });
 }
コード例 #25
0
        public Entities.Customer Map(Domain.Models.Customer model, Entities.PizzaBoxDbContext context, bool update = false)
        {
            Entities.Customer customer = context.Customers.FirstOrDefault(cust => cust.ID == model.ID) ?? new Entities.Customer();
            if (customer.ID != 0 && !update)
            {
                return(customer);
            }
            customer.Name = model.Name;

            if (customer.ID == 0)
            {
                context.Customers.Add(customer);
            }
            return(customer);
        }
コード例 #26
0
        public CustomerViewModel Add(CreateCustomerViewModel createCustomerViewModel)
        {
            var customer = new Domain.Models.Customer(
                createCustomerViewModel.FirstName,
                createCustomerViewModel.LastName,
                createCustomerViewModel.Address,
                createCustomerViewModel.PersonalNumber);

            if (!customer.IsValid())
            {
                throw new DomainException(customer.ValidationResult);
            }

            _customerRepository.Add(customer);
            _customerRepository.SaveChanges();

            return(new CustomerViewModel(customer.Id, customer.FirstName, customer.LastName, customer.Address, customer.PersonalNumber));
        }
コード例 #27
0
        /// <summary>
        /// Right now this is mainly a helper method when placing the order. This is because this returns a Domain.Models.Customer object
        /// That is manipulated by the c# code. The intention was to get the Customer and then set the location and it's inventory
        /// </summary>
        /// <param name="name">Two strings that are valid names.</param>
        /// <returns></returns>
        public Domain.Models.Customer GetCustomerWithLocationAndInventory(int id)
        {
            // first we create our db customer to check if we find it
            Entities.CustomerEntity dbCustomer;

            // if we do then we assign it to the customer
            dbCustomer = _context.Customers
                         .Include(l => l.Location)
                         .Include(sc => sc.Shoppingcarts)
                         .ThenInclude(ci => ci.Cartitems).First(c => c.Id == id);

            // since we found it we map the new customer with the location
            Domain.Models.Customer m_customer = MapperCustomer.MapCustomerWithLocation(dbCustomer);

            // then we get the stocks for the location
            m_customer.MyStoreLocation.Inventory = GetStocksForLocation(m_customer.MyStoreLocation.ID).ToList();

            return(m_customer);
        }
コード例 #28
0
 public ActionResult Create(IFormCollection collection)
 {
     try
     {
         var newCustomer = new Domain.Models.Customer
         {
             FirstName       = collection["FirstName"],
             LastName        = collection["LastName"],
             MyStoreLocation = new Domain.Models.Location {
                 ID = Int32.Parse(collection["allLocations"])
             }
         };
         _repository.AddACustomer(newCustomer);
         return(View(Details(newCustomer.ID)));
     }
     catch
     {
         return(RedirectToAction(nameof(Index)));
     }
 }
        public IEnumerable <object> Handle(GetObjectsCsv query)
        {
            var props    = query.Properties.Split(',');
            var customer = new Domain.Models.Customer();
            var type     = customer.GetType().Assembly.GetType(query.ModelAssemblyFullName);

            var     result = typeof(Repository <>).MakeGenericType(type);
            dynamic inst   = Activator.CreateInstance(result);

            var lista = inst.GetAll(query.Order);

            var listResult = new List <object>();

            foreach (var item in lista)
            {
                var rr = Convert(item, props);
                listResult.Add(rr);
            }
            //var res =((IEnumerable<dynamic>)lista).Select(_ => Convert(_));
            return(listResult);
        }
コード例 #30
0
        /// <summary>
        /// Add a new Customer from Models to Database.
        /// </summary>
        /// <param name="customer"> This is the new Model to be put into the database. It only has a firstname and last name.</param>
        public void AddACustomer(Domain.Models.Customer customer)
        {
            // Create the Entity item to be put into the database
            Entities.CustomerEntity entity;

            // Since the database handles the ID setting with identity, we only need to assign the new entity the firstname and the lastname
            // Maybe in the future we could add a way to change the location, but for now the database sets the location to the default 1.
            entity = MapperCustomer.Map(customer);

            // Add the new entity to the context to send over to the database
            _context.Add(entity);
            Save();

            // Create their shopping cart
            Entities.ShoppingcartEntity shoppingcartEntity = new Entities.ShoppingcartEntity
            {
                CustomerId = entity.Id
            };
            _context.Add(shoppingcartEntity);
            // I am using the aproach of sending the data over after each change instead of having a universal save button
            Save();
        }