Ejemplo n.º 1
0
        public ActionResult Add(ProductDTO item, HttpPostedFileBase FileUrl)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (FileUrl != null)
                    {
                        string FileName = Path.GetFileName(FileUrl.FileName);
                        string path     = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/Content/images/"), FileName);
                        item.FileUrl = FileName;
                        Service.AddProduct(item);

                        FileUrl.SaveAs(path);

                        byte[] imageData;
                        using (var binaryReader = new BinaryReader(FileUrl.InputStream))
                        {
                            imageData = binaryReader.ReadBytes(FileUrl.ContentLength);
                        }
                        Trace.WriteLine(imageData);
                    }
                }
                catch (Exception)
                {
                    ViewBag.FileStatus = "Error while file uploading.";;
                }
            }

            return(View("Add"));
        }
Ejemplo n.º 2
0
        public ActionResult AddProduct(AddProductViewModel productVM, IEnumerable <HttpPostedFileBase> images = null)
        {
            productVM.Regions = locationManager.GetRegions().Skip(1).ToList();
            ViewBag.IsLogged  = true;

            if (ModelState.IsValid)
            {
                if (images != null)
                {
                    foreach (var file in images)
                    {
                        if (file != null)
                        {
                            if (file.FileName.EndsWith(".jpg") || file.FileName.EndsWith(".png") || file.FileName.EndsWith(".img"))
                            {
                                string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
                                file.SaveAs(Server.MapPath("~/Images/" + fileName));
                                productVM.Images.Value.Add(new Image {
                                    ImageUrl = "/Images/" + fileName
                                });
                            }
                        }
                    }
                }
                HttpCookie cookie = HttpContext.Request.Cookies[Constants.NameCookie];
                productVM.User = userManager.GetUserByCookies(cookie.Value);
                productManager.AddProduct(productVM);

                return(RedirectToAction("Index", "Home"));
            }

            return(View(productVM));
        }
Ejemplo n.º 3
0
 public void AddProduct()
 {
     _productManager.AddProduct(new Product(NewProductName, NewProductPrice));
     NewProductName  = "";
     NewProductPrice = 0;
     RefreshProductList(); // lub Products.Add() - czyli niezale¿nie zarz¹dzamy stanem bazy i viewmodelu (przyda³oby siê wtedy sprawdziæ, czy uda³o siê dodaæ do db - AddProduct powinien zwracaæ bool)
 }
Ejemplo n.º 4
0
        public async Task <IActionResult> Post([FromBody] Product newProduct)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var productId = await _productManager.AddProduct(newProduct);

                    if (productId > 0)
                    {
                        return(Ok(productId));
                    }
                    else
                    {
                        return(NotFound());
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, ex.Message);

                    return(BadRequest());
                }
            }

            return(BadRequest());
        }
        public IActionResult Post([FromBody] Product Product)
        {
            if (Product == null)
            {
                return(BadRequest());
            }

            var id = _productManager.AddProduct(Product);

            if (id <= 0)
            {
                ModelState.AddModelError(nameof(Product),
                                         "Hmmm, Product insert failed?");

                // return 422 - Unprocessable Entity
                return(new UnprocessableEntityObjectResult(ModelState));
            }
            else
            {
                Product.Id = id;

                return(CreatedAtRoute("Get",
                                      new { id },
                                      Product));
            }
        }
 public ActionResult Create(Product product)
 {
     if (ModelState.IsValid)
     {
         mgr.AddProduct(product);
         return(RedirectToAction("Index"));
     }
     return(View());
 }
Ejemplo n.º 7
0
        public ActionResult AddProduct([FromBody] ProductFull productFull)
        {
            productFull.Details.DatePublished = DateTime.Now;
            productFull.Product.Code          = _productLogic.generateGUID();

            int productId = _productManager.AddProduct(productFull);

            return(Ok(productId));
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> AddProduct([FromBody] ProductModel model)
        {
            var result = await _productManager.AddProduct(model);

            if (result != null)
            {
                return(Ok(result));
            }
            return(BadRequest("Щось пішло не так. зверніться до оператора технічної підтримки"));
        }
Ejemplo n.º 9
0
        public ActionResult Create(ProductViewModel product)
        {
            if (ModelState.IsValid)
            {
                productManager.AddProduct(MapProductViewModel(product));
                return(RedirectToAction("Index"));
            }

            return(View(product));
        }
Ejemplo n.º 10
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (Option == 0)
            {
                ProductDTO product = new ProductDTO()
                {
                    Name         = textBox1.Text,
                    Price        = Convert.ToInt32(textBox2.Text),
                    TimeOfAdd    = DateTime.Now,
                    CountInStock = Convert.ToInt32(textBox5.Text),
                    Description  = textBox4.Text,
                };

                _productManager.AddProduct(product);
                this.Close();
            }
            else if (Option == 1 && SelectProduct != null)
            {
                string name         = textBox1.Text;
                string price        = textBox2.Text;
                string description  = textBox4.Text;
                string countInStock = textBox5.Text;

                _productManager.DeleteProduct(SelectProduct.Id);
                if (name != "" && price != "" && description != "" && countInStock != "")
                {
                    ProductDTO product = new ProductDTO
                    {
                        CountInStock = Convert.ToInt32(countInStock),
                        Description  = description,
                        Name         = name,
                        Price        = Convert.ToInt32(price),
                        TimeOfAdd    = DateTime.Now
                    };

                    _productManager.AddProduct(product);
                    this.Close();
                }
            }
        }
        public void CreateProduct([FromQuery(Name = "Product")] string productName)
        {
            NewProductNameValidator validator = new NewProductNameValidator(_productManager);
            var results = validator.Validate(productName);

            if (!results.IsValid)
            {
                TempData[TextConstants.TempDataErrorText] = ValidatorHelper.GetErrorString(results.Errors);
                return;
            }

            TempData.Remove(TextConstants.TempDataErrorText);
            _productManager.AddProduct(productName);
        }
Ejemplo n.º 12
0
        public ActionResult Create(ProductViewModel product)
        {
            if (LoginController.active)
            {
                if (ModelState.IsValid)
                {
                    ProductDTO productDTO = _managerP.AddProduct(mapper.Map <ProductDTO>(product));
                    return(RedirectToAction(nameof(Index)));
                }

                return(View());
            }
            return(View("../Login/Index", new LoginViewModel()));
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> CreateProduct([FromBody] ProductModel model)
        {
            var currentUser = CurrentUser();

            model.UserId = currentUser?.Id;

            var prod = await _prodmanager.AddProduct(model);

            return(Ok(new ApiResponse <ProductModel>()
            {
                Data = model,
                Message = "Succeeded",
                StatusCode = HttpStatusCode.OK
            }));
        }
Ejemplo n.º 14
0
        public async Task <Response <Product> > AddProduct(Product product)
        {
            Response <Product> httpResponse = new Response <Product>();

            try
            {
                httpResponse.RequestState = true;
                httpResponse.ErrorState   = !await _productManager.AddProduct(product);
            }
            catch (Exception ex)
            {
                httpResponse.ErrorState = true;
                httpResponse.ErrorList.Add(ex.Adapt <ApiException>());
            }
            return(httpResponse);
        }
        public ActionResult <long> AddProduct([FromBody] ProductInputModel productInputModel)
        {
            var validationResult = _productValidator.ValidateProductInputModelUponCreation(productInputModel);

            if (!string.IsNullOrEmpty(validationResult))
            {
                return(UnprocessableEntity(validationResult));
            }
            var result = _productManager.AddProduct(productInputModel);

            if (!result.ContainsData)
            {
                return(Problem(detail: result.ResponseMessage, statusCode: 520));
            }
            return(Created($"id/{result.Data}", result.Data));
        }
Ejemplo n.º 16
0
        public ActionResult Create(Product Product)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    #region upload files
                    if (!string.IsNullOrEmpty(Product.ImagePaths))
                    {
                        string[] strPicArr     = Product.ImagePaths.Split(';');
                        string   directoryPath = Server.MapPath(pFolderDir);

                        if (!Directory.Exists(directoryPath))
                        {
                            Directory.CreateDirectory(directoryPath);
                        }
                        for (int i = 0; i < strPicArr.Length - 1; i++)
                        {
                            string uploadedFilePath = string.Format("{0}{1}", directoryPath, strPicArr[i]);

                            uploadedFilePath = directoryPath + @"\" + Guid.NewGuid().ToString() + "--" + strPicArr[i];

                            Request.SaveAs(uploadedFilePath, false);
                        }
                    }


                    #endregion

                    objIProdMgr.AddProduct(Product);
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
            }
            finally {  }
            ViewBag.Vendors = BindVendors();

            ViewBag.CategoryId = Product.CategoryId;

            return(View(Product));
        }
Ejemplo n.º 17
0
        public async Task <Response <Product> > AddProduct(AddProductDto product)
        {
            _logger.LogDebug("AddProduct init with", product);
            Response <Product> httpResponse = new Response <Product>();

            try
            {
                httpResponse.RequestState = true;
                httpResponse.ErrorState   = !await _productManager.AddProduct(product);
            }
            catch (Exception ex)
            {
                _logger.LogError("AddProduct Error", ex);
                httpResponse.ErrorState = true;
                httpResponse.ErrorList.Add(ex.Adapt <ApiException>());
            }
            _logger.LogDebug("AddProduct end with", httpResponse);
            return(httpResponse);
        }
        public bool AddProduct(User user, string productName, out Product product, out string error)
        {
            product = default(Product);
            error   = string.Empty;
            bool result;

            try
            {
                _productManager.AddProduct(productName);
                product = _productManager.GetProductByName(productName);
                result  = true;
            }
            catch (Exception e)
            {
                result = false;
                error  = e.Message;
                _logger.LogError(e, $"Failed to add new product name = {productName}, user = {user.UserName}");
            }

            return(result);
        }
Ejemplo n.º 19
0
        public async Task <ActionResult <ProductDTO> > AddProduct(ProductDTO product)
        {
            try
            {
                if (product == null)
                {
                    return(BadRequest("No product provided!"));
                }

                _logger.LogInformation("Adding new product");
                var newProduct = await _productManager.AddProduct(product);

                _logger.LogInformation("Product was added with id: '{0}'", newProduct.ID);

                return(Ok(newProduct));
            }
            catch (Exception)
            {
                _logger.LogError("Error adding product!");
                return(StatusCode(StatusCodes.Status500InternalServerError, "Error adding product!"));
            }
        }
Ejemplo n.º 20
0
        public async Task <JsonResult> AddProduct(ProductDto model)
        {
            var result = await _manager.AddProduct(model);

            if (result == 1)
            {
                _msg = new MsgResult
                {
                    Info      = "新增成功",
                    IsSuccess = true
                };
            }
            else
            {
                _msg = new MsgResult
                {
                    Info      = "新增成功",
                    IsSuccess = true
                };
            }

            return(Json(_msg));
        }
        /// <summary>
        /// Creator: Robert Holmes
        /// Created: 2020/03/18
        /// Approver: Jaeho Kim
        ///
        /// Handles saving product data to the database.
        /// </summary>
        /// <remarks>
        /// Updater:
        /// Updated:
        /// Update:
        ///
        /// </remarks>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAction_Click(object sender, RoutedEventArgs e)
        {
            switch (btnAction.Content)
            {
            case ("Save"):
            {
                if (validateFields())
                {
                    try
                    {
                        _product.ProductID   = txtProductID.Text;
                        _product.ItemID      = Convert.ToInt32(txtItemID.Text);
                        _product.Name        = txtName.Text;
                        _product.Category    = txtCategory.Text;
                        _product.Brand       = txtBrand.Text;
                        _product.Type        = (string)cboType.SelectedItem;
                        _product.Price       = (decimal)numPrice.Value;
                        _product.Description = txtDescription.Text;
                        if ((string)cboTaxable.SelectedItem == "No")
                        {
                            _product.Taxable = false;
                        }
                        else
                        {
                            _product.Taxable = true;
                        }

                        _productManager.AddProduct(_product);

                        _picture.ProductID = _product.ProductID;
                        if (!_picture.IsUsingDefault)
                        {
                            _pictureManager.AddPicture(_picture);
                        }
                    }
                    catch (Exception ex)
                    {
                        WPFErrorHandler.ErrorMessage("Failed to save product to database.\n\n" + ex.Message, ex.GetType().ToString());
                    }
                    _frame.Navigate(new pgInventoryItems(_frame));
                }

                break;
            }

            case "Update":
            {
                if (validateFields())
                {
                    try
                    {
                        var newProduct = new Product
                        {
                            ProductID   = _product.ProductID,
                            ItemID      = Convert.ToInt32(txtItemID.Text),
                            Name        = txtName.Text,
                            Category    = txtCategory.Text,
                            Brand       = txtBrand.Text,
                            Type        = (string)cboType.SelectedItem,
                            Price       = (decimal)numPrice.Value,
                            Description = txtDescription.Text,
                            Active      = _product.Active
                        };
                        if (cboTaxable.SelectedItem.ToString().Equals("No"))
                        {
                            newProduct.Taxable = false;
                        }
                        else
                        {
                            newProduct.Taxable = true;
                        }
                        _productManager.EditProduct(_product, newProduct);
                        _picture.ProductID = _product.ProductID;
                        if (_pictureUpdated)
                        {
                            _pictureManager.AddPicture(_picture);
                        }
                    }
                    catch (Exception ex)
                    {
                        WPFErrorHandler.ErrorMessage("There was a problem saving the new product information:\n\n" + ex.Message);
                    }
                    _frame.Navigate(new pgInventoryItems(_frame));
                }
                break;
            }

            case "Done":
            {
                _frame.Navigate(new pgInventoryItems(_frame));
                break;
            }

            default:
            {
                break;
            }
            }
        }
Ejemplo n.º 22
0
 public async Task <IActionResult> AddProduct(ProductModel product)
 {
     return(Ok(await _productManager.AddProduct(product)));
 }
Ejemplo n.º 23
0
 public void AddProduct(ProductRequest request)
 {
     ValidateRequest(request);
     productManager.AddProduct(request);
 }
Ejemplo n.º 24
0
 public void TestAddProduct()
 {
     productManager.AddProduct(request);
 }