Пример #1
0
        public IActionResult CreateCustomer(CreateCustomerDto customerModel)
        {
            var customerNameOrError  = CustomerName.Create(customerModel.Name);
            var customerEmailOrError = CustomerEmail.Create(customerModel.Email);

            var result = Result.Combine(customerNameOrError, customerEmailOrError);

            if (result.IsFailure)
            {
                return(Error(result.Error));
            }

            if (_customerRepository.GetCustomerByEmail(customerEmailOrError.Value) != null)
            {
                return(Error($"[{customerModel.Email}] is already in use."));
            }

            var customer = new Customer(customerNameOrError.Value, customerEmailOrError.Value);

            _customerRepository.Add(customer);

            return(Ok());

            // return CreatedAtAction(nameof(GetCustomerById), new {id = customerModel.Id}, customerModel);
        }
Пример #2
0
        public ActionResult CreateCustomer(CustomerModel customerModel)
        {
            Result <CustomerName> customerNameResult = CustomerName.Create(customerModel.Name);
            Result <Email>        emailResult        = Email.Create(customerModel.Email);

            if (customerNameResult.IsFailure)
            {
                ModelState.AddModelError("Name", customerNameResult.Error);
            }
            if (emailResult.IsFailure)
            {
                ModelState.AddModelError("Email", emailResult.Error);
            }

            if (!ModelState.IsValid)
            {
                return(View(customerModel));
            }

            var customer = new Customer(customerNameResult.Value, emailResult.Value);

            // _database.Save(customer);

            return(RedirectToAction("Index"));
        }
        public IActionResult Create([FromBody] CreateCustomerDto item)
        {
            try
            {
                Result <CustomerName> customerNameOrError = CustomerName.Create(item.Name);
                Result <Email>        emailOrError        = Email.Create(item.Email);

                Result result = Result.Combine(customerNameOrError, emailOrError);
                if (result.IsFailure)
                {
                    return(BadRequest(result.Error));
                }

                if (_customerRepository.GetByEmail(emailOrError.Value) != null)
                {
                    return(BadRequest("Email is already by another user " + item.Email));
                }

                var customer = new Customer(customerNameOrError.Value, emailOrError.Value);
                _customerRepository.Add(customer);

                return(Ok(item));
            }
            catch (Exception e)
            {
                return(StatusCode(500, new { error = e.Message }));
            }
        }
Пример #4
0
        public IActionResult Create([FromBody] CreateCustomerDto item)
        {
            Result <CustomerName> customerNameOrError = CustomerName.Create(item.FullName);
            Result <Email>        emailOrError        = Email.Create(item.Email);

            Result result = Result.Combine(customerNameOrError, emailOrError);

            if (result.IsFailure)
            {
                return(BadRequest(result.Error));
            }

            if (_customerRepository.GetByEmail(emailOrError.Value) != null)
            {
                return(BadRequest("Email is already in use: " + item.Email));
            }

            var customer = new Customer(customerNameOrError.Value, emailOrError.Value);

            bool uowStatus = false;

            try
            {
                uowStatus = _unitOfWork.BeginTransaction();
                _customerRepository.Create(customer);
                _unitOfWork.Commit(uowStatus);
                return(StatusCode(StatusCodes.Status200OK));
            } catch (Exception ex)
            {
                _unitOfWork.Rollback(uowStatus);
                Console.WriteLine(ex.StackTrace);
                return(StatusCode(StatusCodes.Status500InternalServerError, new ApiStringResponseDto("Internal Server Error")));
            }
        }
Пример #5
0
        public IActionResult Update(long id, [FromBody] UpdateCustomerDto item)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var customerNameOrError = CustomerName.Create(item.Name);

                if (customerNameOrError.IsFailure)
                {
                    return(BadRequest(customerNameOrError.Error));
                }

                Customer customer = _customerRepository.GetById(id);
                if (customer == null)
                {
                    return(BadRequest("Invalid customer id: " + id));
                }

                customer.Name = customerNameOrError.Value;
                _customerRepository.SaveChanges();

                return(Ok());
            }
            catch (Exception e)
            {
                return(StatusCode(500, new { error = e.Message }));
            }
        }
Пример #6
0
        public static void PopulateTestData(IECommerceDbContext dbContext)
        {
            dbContext.Customers.Add(new Customer(CustomerName.Create("John"), Email.Create("*****@*****.**")));
            dbContext.Customers.Add(new Customer(CustomerName.Create("Ana"), Email.Create("*****@*****.**")));

            dbContext.SaveChanges();
        }
Пример #7
0
        public IActionResult Create([FromBody] CreateCustomerDto item)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var customerNameOrError = CustomerName.Create(item.Name);
                var emailOrError        = Email.Create(item.Email);

                var result = Result.Combine(customerNameOrError, emailOrError);
                if (result.IsFailure)
                {
                    return(BadRequest(result.Error));
                }

                if (_customerRepository.GetByEmail(emailOrError.Value) != null)
                {
                    return(BadRequest("Email is already in use: " + item.Email));
                }

                var customer = new Customer(customerNameOrError.Value, emailOrError.Value);
                _customerRepository.Add(customer);
                _customerRepository.SaveChanges();

                return(Ok());
            }
            catch (Exception e)
            {
                return(StatusCode(500, new { error = e.Message }));
            }
        }
Пример #8
0
        public async Task <Customer4A4> Get(Guid customerId)
        {
            using (var conn = new SqlConnection())
            {
                var customerData = await conn.QuerySingleOrDefaultAsync <CustomerData4A>(
                    "SELECT * FROM Customers WHERE CustomerId = @customerId",
                    new { customerId });

                var addressesData = await conn.QueryAsync <AddressData4A>(
                    "SELECT * FROM Addresses WHERE Customer",
                    new { customerId });

                var nameResult = CustomerName.Create(customerData.Title,
                                                     customerData.FirstName,
                                                     customerData.LastName);
                var dobResult        = Dob.Create(customerData.DateOfBirth);
                var idDocumentResult = IdDocument.Create(customerData.IdDocumentType,
                                                         customerData.IdDocumentNumber);

                var addresses = addressesData.Select(a => Address4A.Create(a.AddressId,
                                                                           a.HouseNoOrName,
                                                                           a.Street,
                                                                           a.City,
                                                                           a.County,
                                                                           a.PostCode,
                                                                           a.CurrentAddress).Value);

                return(new Customer4A4(customerData.CustomerId,
                                       nameResult.Value,
                                       dobResult.Value,
                                       idDocumentResult.Value,
                                       addresses));
            }
        }
        public IActionResult Create([FromBody] CreateCustomerDto item)
        {
            Result <CustomerName> customerNameOrError = CustomerName.Create(item.Name);
            Result <Email>        emailOrError        = Email.Create(item.Email);

            Result result = Result.Combine(customerNameOrError, emailOrError);

            if (result.IsFailure)
            {
                return(Error(result.Error));
            }


            if (_customerRepository.GetByEmail(emailOrError.Value) != null)
            {
                return(Error("Email is already in use: " + item.Email));
            }

            var customer = new Customer(customerNameOrError.Value, emailOrError.Value);

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

            return(Ok());
        }
Пример #10
0
        private static Result <Customer> CreateCustomer1(string email, string customerName)
        {
            // Email
            Result <Email> emailResult = Email.Create(email);

            if (emailResult.IsFailure)
            {
                return(Result.Failure <Customer>(emailResult.Error));
            }

            Email emailObj = emailResult.Value;

            // CustomerName
            Result <CustomerName> customerNameResult = CustomerName.Create(customerName);

            if (customerNameResult.IsFailure)
            {
                return(Result.Failure <Customer>(customerNameResult.Error));
            }

            CustomerName customerNameObj = customerNameResult.Value;

            // Customer
            return(new Customer(emailObj, customerNameObj));
        }
Пример #11
0
 public void Create_ShouldThrowExceptionForInvalidCustomerName(string name)
 {
     FluentActions
     .Invoking(() => CustomerName.Create(name))
     .Should()
     .Throw <Exception>()
     .WithMessage("Customer name should not be empty.");
 }
Пример #12
0
        public void Create_ShouldSetTheValue()
        {
            const string name = "John";

            var result = CustomerName.Create(name);

            result.Value.Should().Be(name);
        }
Пример #13
0
        public void ImplicitConversionToString_ShouldConvertToTheCorrectString()
        {
            const string name         = "John";
            var          customerName = CustomerName.Create(name);

            var result = (string)customerName;

            result.Should().Be(name);
        }
Пример #14
0
        public void Equals_ShouldReturnTheCorrectResult(string name1, string name2, bool expectedResult)
        {
            var customerName1 = CustomerName.Create(name1);
            var customerName2 = CustomerName.Create(name2);

            var result = customerName1 == customerName2;

            result.Should().Be(expectedResult);
        }
Пример #15
0
        private static Result <Customer> CreateCustomer2(string email, string customerName)
        {
            var emailResult        = Email.Create(email);
            var customerNameResult = CustomerName.Create(customerName);

            return(Result
                   .Combine(emailResult, customerNameResult)
                   .Map(() => new Customer(emailResult.Value, customerNameResult.Value)));
        }
Пример #16
0
        public void Create_WithInvalidSecondAddressAndInvalidCombinationOfNameAndMainAddress_ShouldReturnAllErrorMessages()
        {
            var nameResult          = CustomerName.Create("Altmann");
            var mainAddressResult   = Address.Create("Str", "1");
            var secondAddressResult = Address.Create("Street2", "2");

            var customerResult = Customer.Create(nameResult.Value, mainAddressResult.Value, secondAddressResult.Value);

            // Passing Value Object in Customer.Create(...) is not possible because Value Objects have to be valid.
        }
Пример #17
0
        public void Create_ShouldThrowExceptionForTooLongCustomerName()
        {
            var name = new string('A', 310);

            FluentActions
            .Invoking(() => CustomerName.Create(name))
            .Should()
            .Throw <Exception>()
            .WithMessage("Customer name is too long.");
        }
Пример #18
0
        public async Task <ActionResult <Guid> > Post([FromBody] CustomerRequest3A request)
        {
            // value objects validate their inputs
            var nameResult = CustomerName.Create(request.Title,
                                                 request.FirstName,
                                                 request.LastName);

            if (nameResult.Status == OperationStatus.ValidationFailure)
            {
                return(BadRequest(nameResult.ErrorMessages));
            }

            var dobResult = Dob.Create(request.DateOfBirth);

            if (dobResult.Status == OperationStatus.ValidationFailure)
            {
                return(BadRequest(dobResult.ErrorMessages));
            }

            var idDocumentResult = IdDocument.Create(request.IdDocumentType,
                                                     request.IdDocumentNumber);

            if (idDocumentResult.Status == OperationStatus.ValidationFailure)
            {
                return(BadRequest(idDocumentResult.ErrorMessages));
            }

            // convert request DTO to domain model
            var customer = new Customer3A(request.CustomerId,
                                          nameResult.Value,
                                          dobResult.Value,
                                          idDocumentResult.Value,
                                          request.Addresses.Select(a => new Address3A(a.HouseNoOrName,
                                                                                      a.Street,
                                                                                      a.City,
                                                                                      a.County,
                                                                                      a.PostCode,
                                                                                      a.CurrentAddress
                                                                                      )));

            // command just wrap domain model
            var response = await _mediator.Send(new CreateCustomerCommand3A(customer));

            var apiResponse = new CreateCustomerApiResponse3A(response.Value);

            if (response.Status == OperationStatus.Conflict)
            {
                return(Conflict(apiResponse));
            }

            return(Created($"/customers/customer/{apiResponse.CustomerId}", apiResponse));
        }
Пример #19
0
        public async Task HandleAsync(RegisterCustomerCommand command)
        {
            var customerName = CustomerName
                               .Create(command.CustomerName);

            var customer = new Customer(customerName.Value);

            _repository
            .Add(customer);

            await _unitOfWork
            .CommitAsync();
        }
Пример #20
0
        public void Create_WithInvalidSecondAddressAndInvalidCombinationOfNameAndMainAddress_ShouldReturnAllErrorMessages()
        {
            var nameResult          = CustomerName.Create("Altmann");
            var mainAddressResult   = Address.Create("Str", "1");
            var secondAddressResult = Address.Create("Street2", "2");

            var customerResult = Customer.Create(nameResult, mainAddressResult, secondAddressResult);

            var validationResult = Result.Combine(
                nameResult,
                mainAddressResult,
                secondAddressResult,
                customerResult);

            validationResult.Error.Should().Be("Street Length > 5, If name starts with A then street should also start with A.");
        }
        public async Task <long> Handle(CreateCustomerCommand request, CancellationToken cancellationToken)
        {
            var customerName = CustomerName.Create(request.Name);
            var email        = Email.Create(request.Email);

            if (_customerRepository.GetByEmailAsync(email) != null)
            {
                throw new Exception($"Email {email} is already in use.");
            }

            var entity = new Customer(customerName, email);

            await _customerRepository.AddAsync(entity);

            return(entity.Id);
        }
Пример #22
0
        public void Configure(EntityTypeBuilder <Customer> builder)
        {
            builder
            .HasKey(k => k.Id);

            builder
            .HasMany(p => p.Addresses)
            .WithOne()
            .OnDelete(DeleteBehavior.Cascade)
            .Metadata.PrincipalToDependent.SetPropertyAccessMode(PropertyAccessMode.Field);

            builder.Property(p => p.CustomerName)
            .HasConversion(p => p.Value,
                           p => CustomerName.Create(p).Value)
            .IsRequired()
            .HasMaxLength(80)
            .HasColumnType("varchar");
        }
        public IActionResult Update(long id, [FromBody] UpdateCustomerDto item)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Customer customer = _customerRepository.GetById(id);

            if (customer == null)
            {
                return(Error("Invalid customer id: " + id));
            }

            customer.Name = CustomerName.Create(item.Name).Value;

            return(Ok());
        }
Пример #24
0
        public IActionResult Create([FromBody] CreateCustomerDto item)
        {
            //No need for try catch stm since they are managed by the middleware.
            //try
            //{
            Result <CustomerName> customerNameOrError = CustomerName.Create(item.Name);
            Result <Email>        emailOrError        = Email.Create(item.Email);
            Result result = Result.Combine(customerNameOrError, emailOrError);

            if (result.IsFailure)
            {
                //return BadRequest(result.Error);
                return(Error(result.Error));
            }

            //if (!ModelState.IsValid)
            //{
            //    return BadRequest(ModelState);
            //}

            //This business rule should be elsewhere
            if (_customerRepository.GetByEmail(emailOrError.Value) != null)
            {
                //return BadRequest("Email is already in use: " + item.Email);
                return(Error("Email is already in use: " + item.Email));
            }
            var customer = new Customer(customerNameOrError.Value, emailOrError.Value);

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


            return(CreatedAt(new { id = customer.Id }, Result <CreateCustomerDto> .Ok(new CreateCustomerDto {
                Email = customer.Email, Name = customer.Name
            })));

            //return CreatedAtAction(nameof(Get), new { id = customer.Id }, new CreateCustomerDto { Email= customer.Email, Name= customer.Name});
            ///return Ok();
            //}
            //catch (Exception e)
            //{
            //    return StatusCode(500, new { error = e.Message });
            //}
        }
Пример #25
0
        public IActionResult Update(long id, [FromBody] UpdateCustomerDto item)
        {
            Result <CustomerName> customerNameOrError = CustomerName.Create(item.FirstName);

            if (customerNameOrError.IsFailure)
            {
                return(BadRequest(customerNameOrError.Error));
            }

            Customer customer = _customerRepository.Read(id);

            if (customer == null)
            {
                return(BadRequest("Invalid customer id: " + id));
            }

            customer.FirstName = customerNameOrError.Value;

            return(Ok());
        }
Пример #26
0
        public HttpResponseMessage Create(CreateCustomerModel model)
        {
            Result <CustomerName>   customerName   = CustomerName.Create(model.Name);
            Result <Email>          primaryEmail   = Email.Create(model.PrimaryEmail);
            Result <Maybe <Email> > secondaryEmail = GetSecondaryEmail(model.SecondaryEmail);
            Result <Industry>       industry       = Industry.Get(model.Industry);

            Result result = Result.Combine(customerName, primaryEmail, secondaryEmail, industry);

            if (result.IsFailure)
            {
                return(Error(result.Error));
            }

            var customer = new Customer(customerName.Value, primaryEmail.Value, secondaryEmail.Value, industry.Value);

            _customerRepository.Save(customer);

            return(Ok());
        }
Пример #27
0
        public IActionResult UpdateCustomer(long id, UpdateCustomerDto customerModel)
        {
            var customerNameOrError = CustomerName.Create(customerModel.Name);

            if (customerNameOrError.IsFailure)
            {
                return(Error(customerNameOrError.Error));
            }

            var customer = _customerRepository.GetById(id);

            if (customer == null)
            {
                return(Error($"[{id}] is an invalid customer id"));
            }

            customer.Name = customerNameOrError.Value;

            return(Ok(customer));
        }
Пример #28
0
        public IActionResult Update(long id, [FromBody] UpdateCustomerDto item)
        {
            var customerNameOrError = CustomerName.Create(item.Name);

            if (customerNameOrError.IsFailure)
            {
                return(Error(customerNameOrError.Error));
            }

            Customer customer = _customerRepository.GetById(id);

            if (customer == null)
            {
                return(Error("Invalid customer id: " + id));
            }

            customer.Name = customerNameOrError.Value;

            return(Ok());
        }
        public IActionResult Create(CreateCustomerDto dto)
        {
            Result <CustomerName>   customerName   = CustomerName.Create(dto.Name);
            Result <Email>          primaryEmail   = Email.Create(dto.PrimaryEmail);
            Result <Maybe <Email> > secondaryEmail = GetSecondaryEmail(dto.SecondaryEmail);
            Result <Industry>       industry       = Industry.Get(dto.Industry);

            Result result = Result.Combine(customerName, primaryEmail, secondaryEmail, industry);

            if (result.IsFailure)
            {
                return(Error(result.Error));
            }

            var customer = new Customer(customerName.Value, primaryEmail.Value, secondaryEmail.Value, industry.Value);

            customerRepository.Save(customer);

            return(Ok());
        }
Пример #30
0
        public async Task <IActionResult> Update(string id, [FromBody] UpdateCustomerDto item)
        {
            Result <CustomerName> customerNameOrError = CustomerName.Create(item.Name);

            if (customerNameOrError.IsFailure)
            {
                return(Error(customerNameOrError.Error));
            }

            Customer customer = await DocumentDBRepository <Customer> .GetItemAsync(id);

            if (customer == null)
            {
                return(Error("Invalid customer id: " + id));
            }

            customer.Name = customerNameOrError.Value;
            await DocumentDBRepository <Customer> .UpdateItemAsync(id, customer);

            return(Ok());
        }