Esempio n. 1
0
        public int New(OrderNew viewModel)
        {
            Order order = null;

            order = new Order()
            {
                Address1   = viewModel.Address1,
                Address2   = viewModel.Address2,
                City       = viewModel.City,
                CountryId  = viewModel.CountryCode,
                Country    = db.Countries.First(c => c.Id == viewModel.CountryCode.ToLower()),
                Email      = viewModel.Email,
                Firstname  = viewModel.Firstname,
                Name       = viewModel.Name,
                Salutation = viewModel.Salutation,
                Zip        = viewModel.Zip,
                Comment    = viewModel.Comment
            };

            var productIdsAndQtys = viewModel.Products.ToDictionary(
                k => k.Id,
                v => v.Qty);

            new ShopService().PlaceOrder(db, order, productIdsAndQtys);

            return(order.Id);
        }
Esempio n. 2
0
        public async Task Create_Method_Adds_Provided_Order_To_Context()
        {
            var order = OrdersSeed.Orders.Value.FirstOrDefault();

            Assert.NotNull(order);

            using (var scope = this._repoScopeCreate())
            {
                var orderNew = OrderNew.From(order);

                var created = await scope.Repository.Create(orderNew);

                Assert.NotNull(created);
                Assert.True(created.OrderId == orderNew.OrderId);
                Assert.True(created.CustomerName == orderNew.CustomerName);
                Assert.True(created.PostCode == orderNew.PostCode);
                Assert.True(created.HouseNumber == orderNew.HouseNumber);
                Assert.True(created.Price == orderNew.Price);
            }

            using (var scope = this._repoScopeCreate())
            {
                var saved = await scope.Repository.Get(OrderId.FromString(order.OrderId));

                Assert.NotNull(saved);
            }
        }
Esempio n. 3
0
        public async Task PaginatedGet_Method_Returns_Paginated_Result_Of_Orders()
        {
            var paging = Paging.Default;

            paging.IncludeTotalCnt = true;

            using (var scope = this._repoScopeCreate())
            {
                foreach (var order in OrdersSeed.Orders.Value)
                {
                    var orderNew = OrderNew.From(order);
                    await scope.Repository.Create(orderNew);
                }
            }

            using (var scope = this._repoScopeCreate())
            {
                var result = await scope.Repository.Get(paging);

                Assert.NotNull(result);
                Assert.True(result.TotalCount == OrdersSeed.Orders.Value.Count);
                Assert.True(result.Skipped == paging.Skip);
                Assert.True(result.Take <= paging.Take);
            }
        }
Esempio n. 4
0
        public async Task Delete_Method_Removes_Specified_Order_From_Context()
        {
            var order = OrdersSeed.Orders.Value.FirstOrDefault();

            Assert.NotNull(order);

            var orderNew = OrderNew.From(order);
            var orderId  = OrderId.FromString(orderNew.OrderId);

            using (var scope = this._repoScopeCreate())
            {
                await scope.Repository.Create(orderNew);
            }

            using (var scope = this._repoScopeCreate())
            {
                await scope.Repository.Delete(orderId);
            }

            using (var scope = this._repoScopeCreate())
            {
                var deleted = await scope.Repository.Get(orderId);

                Assert.Null(deleted);
            }
        }
        public async Task <Orders.Contracts.Models.Order> Create(OrderNew newOrder)
        {
            if (newOrder == null)
            {
                throw new ArgumentNullException(nameof(newOrder));
            }

            var order = this._mapper.Map <Order>(newOrder);

            var entry = await this._dbContext.Orders.AddAsync(order);

            try
            {
                await this._dbContext.SaveChangesAsync();
            }
            catch (ArgumentException ex)
            {
                throw new OrderExistsException(order.OrderId, ex);
            }
            catch (DbUpdateException ex)
            {
                throw new OrderExistsException(order.OrderId, ex);
            }

            return(this._mapper.Map <Orders.Contracts.Models.Order>(entry.Entity));
        }
Esempio n. 6
0
        public int Add(OrderNew data)
        {
            int orderId = 0;

            using (SqlConnection connection = new SqlConnection(this.connectionString))
            {
                connection.Open();

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = @"INSERT INTO Orders
                                          (	                                     
	                                          CustomerID,
                                              EmployeeID,
	                                          OrderDate,
                                              RequiredDate,
	                                          ShippedDate,
                                              ShipperID,
	                                          Freight,
                                              ShipAddress,
	                                          ShipCity,
                                              ShipCountry,
                                              Status	                                          
                                          )
                                          VALUES
                                          (
	                                          @CustomerID,
                                              @EmployeeID,
	                                          @OrderDate,
                                              @RequiredDate,
	                                          @ShippedDate,
                                              @ShipperID,
	                                          @Freight,
                                              @ShipAddress,
	                                          @ShipCity,
                                              @ShipCountry,
                                              @Status
                                          );
                                          SELECT @@IDENTITY;";
                cmd.CommandType = CommandType.Text;
                cmd.Connection  = connection;
                cmd.Parameters.AddWithValue("@CustomerID", data.CustomerID);
                cmd.Parameters.AddWithValue("@EmployeeID", data.EmployeeID);
                cmd.Parameters.AddWithValue("@OrderDate", data.OrderDate);
                cmd.Parameters.AddWithValue("@RequiredDate", data.RequiredDate);
                cmd.Parameters.AddWithValue("@ShippedDate", data.ShippedDate);
                cmd.Parameters.AddWithValue("@ShipperID", data.ShipperID);
                cmd.Parameters.AddWithValue("@Freight", data.Freight);
                cmd.Parameters.AddWithValue("@ShipAddress", data.ShipAddress);
                cmd.Parameters.AddWithValue("@ShipCity", data.ShipCity);
                cmd.Parameters.AddWithValue("@ShipCountry", data.ShipCountry);
                cmd.Parameters.AddWithValue("@Status", "queue");

                orderId = Convert.ToInt32(cmd.ExecuteScalar());

                connection.Close();
            }

            return(orderId);
        }
 public OrderNewTests()
 {
     Source = new OrderNew()
     {
         CustomerName = "Test Name",
         HouseNumber  = 1,
         OrderId      = "SAL123456",
         PostCode     = "1541UT",
         Price        = 20m
     };
 }
        public void OrderNew_Creates_A_Copy_Of_Provided_Source()
        {
            var copy = OrderNew.From(Source);

            Assert.True(copy != Source);
            Assert.Equal(copy.OrderId, Source.OrderId);
            Assert.Equal(copy.HouseNumber, Source.HouseNumber);
            Assert.Equal(copy.PostCode, Source.PostCode);
            Assert.Equal(copy.Price, Source.Price);
            Assert.Equal(copy.CustomerName, Source.CustomerName);
        }
        public async Task <Order> Create(OrderNew order)
        {
            if (order == null)
            {
                throw new ArgumentNullException(nameof(order));
            }

            var created = await this._ordersRepository.Create(order);

            return(created);
        }
        public async Task Create_Method_Calls_Create_Method_Of_IOrdersRepository_In_Order_To_Execute_A_Call()
        {
            var order = OrdersSeed.Orders.Value.FirstOrDefault();

            Assert.NotNull(order);

            var orderNew = OrderNew.From(order);

            await Service.Create(orderNew);

            this.Repository.Verify(repository => repository.Create(orderNew), Times.Once);
            this.Repository.VerifyNoOtherCalls();
        }
        public void OrderNew_Creates_A_Copy_Of_Provided_Source_And_Can_Supply_A_Callback_To_Perform_Extra_Actions_On_Copy()
        {
            var updatedName = "Updated";

            var copy = OrderNew.From(Source, order => order.CustomerName = updatedName);

            Assert.True(copy != Source);
            Assert.Equal(copy.OrderId, Source.OrderId);
            Assert.Equal(copy.HouseNumber, Source.HouseNumber);
            Assert.Equal(copy.PostCode, Source.PostCode);
            Assert.Equal(copy.Price, Source.Price);
            Assert.NotEqual(copy.CustomerName, Source.CustomerName);
            Assert.True(copy.CustomerName == updatedName);
        }
 public ActionResult AddOrder(string id = "")
 {
     if (string.IsNullOrEmpty(id))
     {
         ViewBag.Title      = "Create Order";
         ViewBag.SmallTitle = "Thêm Order";
         OrderNew newOrder = new OrderNew()
         {
             OrderID = 0,
         };
         return(View(newOrder));
     }
     return(View());
 }
        public async Task <IActionResult> PlaceOrder([FromBody] OrderNew orderNew)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var createdOrder = await this._ordersManagementService.Create(orderNew);

            var url = Url.Action(nameof(GetOrder), new OrderIdQuery {
                OrderId = createdOrder.OrderId
            });

            return(Created(url, createdOrder));
        }
Esempio n. 14
0
        protected void ddlQty_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddl = sender as DropDownList;
            int          selectedQty;

            if (Int32.TryParse(ddl.SelectedValue, out selectedQty))
            {
                RepeaterItem item  = (RepeaterItem)ddl.NamingContainer;
                HiddenField  field = (HiddenField)item.FindControl("ProdAttrID");
                int          prodAttrId;
                if (Int32.TryParse(field.Value, out prodAttrId))
                {
                    SHOPPING_CART cart;
                    if ((cart = CartSession.Where(c => c.ID == CartID && c.ProdAttrID == prodAttrId).FirstOrDefault()) != null)
                    {
                        // we already have the right version in the session variable cartsession
                        int      oldQuantity = cart.Quantity;
                        DateTime oldDate     = cart.DateAdded;
                        cart.Quantity  = selectedQty;
                        cart.DateAdded = DateTime.Now;
                        try
                        {
                            ApplicationContext.Current.Carts.Update(cart, oldQuantity);
                        }
                        catch (Exception ex)
                        {
                            OrderNew parent = this.Page as OrderNew;
                            parent.writeResult(ex.Message, true);

                            // reverse situation because of optimistic error
                            cart.Quantity  = oldQuantity;
                            cart.DateAdded = oldDate;
                        }
                        // refresh session, optional
                        //CartSession = ApplicationContext.Current.Carts.GetShoppingCartItems(CartID);
                        DataBind(CartSession);
                        // notify parent for a partial refresh
                        NeedRefresh(sender, e);
                        ddl.Enabled = false;
                        LinkButton lnk = (LinkButton)item.FindControl("lnkEdit");
                        lnk.Enabled = false;
                    }
                }
            }
        }
Esempio n. 15
0
        public override IEnumerable <object[]> GetData(MethodInfo testMethod)
        {
            var validOrder = OrdersSeed.Orders.Value.FirstOrDefault();

            Assert.NotNull(validOrder);

            var orders = new[]
            {
                new [] { OrderNew.From(validOrder, order => { order.CustomerName = new String('A', OrderConstants.CustomerName.MinLength - 1); }) },
                new [] { OrderNew.From(validOrder, order => { order.CustomerName = new String('A', OrderConstants.CustomerName.MaxLength + 1); }) },
                new [] { OrderNew.From(validOrder, order => { order.CustomerName = "N"; }) },
                new [] { OrderNew.From(validOrder, order => { order.PostCode = "12345"; }) },
                new [] { OrderNew.From(validOrder, order => { order.OrderId = "ASFG23124124"; }) },
                new [] { OrderNew.From(validOrder, order => { order.HouseNumber = 0; }) },
                new [] { OrderNew.From(validOrder, order => { order.Price = 0m; }) },
                new IOrderNew[] { new OrderNew() }
            };

            return(orders);
        }
Esempio n. 16
0
        public async Task Create_Method_Throws_If_Order_With_Provided_Id_Exists_In_Context()
        {
            var order = OrdersSeed.Orders.Value.FirstOrDefault();

            Assert.NotNull(order);

            var orderNew = OrderNew.From(order);

            using (var scope = this._repoScopeCreate())
            {
                await scope.Repository.Create(orderNew);
            }

            using (var scope = this._repoScopeCreate())
            {
                var ex = await Assert.ThrowsAsync <OrderExistsException>(() => scope.Repository.Create(orderNew));

                Assert.True(ex.OrderId == orderNew.OrderId);
            }
        }
Esempio n. 17
0
        public virtual ActionResult Index(PostOrderNew viewModel)
        {
            if (ModelState.IsValid)
            {
                try {
                    var order = new Order()
                    {
                        Address1   = viewModel.Address1,
                        Address2   = viewModel.Address2,
                        City       = viewModel.City,
                        CountryId  = viewModel.CountryCode,
                        Country    = db.Countries.First(c => c.Id == viewModel.CountryCode.ToLower()),
                        Email      = viewModel.Email,
                        Firstname  = viewModel.Firstname,
                        Name       = viewModel.Name,
                        Salutation = viewModel.Salutation,
                        Zip        = viewModel.Zip,
                        Comment    = viewModel.Comment
                    };

                    var productIdsAndQtys = viewModel.Products.ToDictionary(
                        k => k.Id,
                        v => v.Qty);

                    new ShopService().PlaceOrder(db, order, productIdsAndQtys);

                    return(viewModel.UsesPayPal
                        ? RedirectToAction("create", "paypal", new { orderId = order.Id })
                        : RedirectToAction("success", new { id = order.Id }));
                }
                catch (AppException e) {
                    Error(e.Message);
                }
            }

            // ViewModel um die Länder anreichern.
            var vm = new OrderNew(db.Countries);

            return(View("index", Mapper.Map(viewModel, vm)));
        }
        public async Task PlaceOrder_Returns_Newly_Created_Order_With_Location_Headers_Set()
        {
            var newOrder = new OrderNew
            {
                CustomerName = "Ivan M",
                HouseNumber  = 12,
                OrderId      = "SAL1005236",
                PostCode     = "1673AO",
                Price        = 20.0m
            };

            var content = new StringContent(JsonConvert.SerializeObject(newOrder), Encoding.UTF8, "application/json");

            var response = await this.Client.PostAsync(Routes.Orders, content);

            Assert.True(response.StatusCode == HttpStatusCode.Created);
            Assert.True(response.Headers.Location.OriginalString == Routes.OrderUrl(newOrder.OrderId));
            var order = await response.GetFromBody <Order>();

            Assert.NotNull(order);
            Assert.True(order.OrderId == newOrder.OrderId);
        }
        public async Task PlaceOrder_Fails_When_Attempt_To_Create_Order_With_Existing_OrderId()
        {
            var existingOrder = OrdersSeed.Orders.Value.FirstOrDefault();

            Assert.NotNull(existingOrder);

            var newOrder = new OrderNew
            {
                CustomerName = "Ivan M",
                HouseNumber  = 12,
                OrderId      = existingOrder.OrderId,
                PostCode     = "1673AO",
                Price        = 20.0m
            };

            var response = await this.Client.PostAsync(Routes.Orders, newOrder.AsStringContent());

            Assert.True(response.StatusCode == HttpStatusCode.InternalServerError);
            var error = await response.GetFromBody <ExposableApiError>();

            Assert.NotNull(error);
            Assert.True(!string.IsNullOrEmpty(error.Reason));
        }
Esempio n. 20
0
        public async Task Update_Method_Updates_Specified_Order_And_Returns_Updated_Order()
        {
            var order = OrdersSeed.Orders.Value.FirstOrDefault();

            Assert.NotNull(order);

            var orderNew = OrderNew.From(order);
            var orderId  = OrderId.FromString(orderNew.OrderId);

            using (var scope = this._repoScopeCreate())
            {
                await scope.Repository.Create(orderNew);
            }

            using (var scope = this._repoScopeCreate())
            {
                var orderUpdate = OrderUpdate.From(order, update => update.CustomerName = "New Top Customer");
                var updated     = await scope.Repository.Update(orderId, orderUpdate);

                Assert.NotNull(updated);
                Assert.True(updated.OrderId == orderId.Value);
                Assert.True(updated.CustomerName == orderUpdate.CustomerName);
            }
        }
        public ActionResult AddOrder(OrderNew model)
        {
            //TODO: Kiểm tra tính hợp lệ của dữ liệu được nhập
            if (string.IsNullOrEmpty(model.CustomerID))
            {
                ModelState.AddModelError("CustomerID", "CustomerID Expected");
            }
            if (model.EmployeeID == 0)
            {
                ModelState.AddModelError("EmployeeID", "EmployeeID Expected");
            }
            if (model.ShipperID == 0)
            {
                ModelState.AddModelError("ShipperID", "ShipperID Expected");
            }
            if (string.IsNullOrEmpty(model.ShipCountry))
            {
                ModelState.AddModelError("ShipCountry", "ShipCountry Expected");
            }

            if (model.OrderDate == null)
            {
                ModelState.AddModelError("OrderDate", "OrderDate Expected");
            }
            if (model.RequiredDate == null)
            {
                ModelState.AddModelError("RequiredDate", "RequiredDate Expected");
            }
            if (model.ShippedDate == null)
            {
                ModelState.AddModelError("ShippedDate", "ShippedDate Expected");
            }

            if (string.IsNullOrEmpty(model.Freight.ToString()))
            {
                model.Freight = 0;
            }
            if (string.IsNullOrEmpty(model.ShipAddress))
            {
                model.ShipAddress = "";
            }
            if (string.IsNullOrEmpty(model.ShipCity))
            {
                model.ShipCity = "";
            }

            if (!ModelState.IsValid)
            {
                ViewBag.Title = model.OrderID == 0 ? "Create new Order" : "Edit Order";
                return(View(model));
            }
            //TODO: Lưu dữ liệu vao DB


            if (model.OrderID == 0)
            {
                CatalogBLL.AddOrderNew(model);
            }

            return(RedirectToAction("Create"));
        }
        public async Task PlaceOrder_Returns_A_List_Of_Validation_Errors_When_OrderNew_Model_Is_Not_Valid(OrderNew newOrder)
        {
            var response = await this.Client.PostAsync(Routes.Orders, newOrder.AsStringContent());

            Assert.True(response.StatusCode == HttpStatusCode.BadRequest);
            var validationErrors = await response.GetFromBody <Dictionary <string, object> >();

            Assert.NotNull(validationErrors);
            Assert.True(validationErrors.Keys.Count > 0);
        }
Esempio n. 23
0
 public static int AddOrderNew(OrderNew data)
 {
     return(OrderNewDB.Add(data));
 }