示例#1
0
        public ActionResult ShowBySlug(string catSlug, string Slug)
        {
            var cat = _categoryService.GetBySlug(catSlug);

            if (cat == null && !cat.IsProduct)
            {
                return(RedirectToAction("index", "Catergory"));
            }

            var topic = _productSevice.GetBySlug(Slug);

            if (topic == null || cat.Id != topic.Category_Id)
            {
                return(RedirectToAction("ShowBySlugProduct", "Category", new { slug = cat.Slug }));
            }

            ProductPost post = new ProductPost();

            if (topic.ProductPost_Id != null)
            {
                post = _productPostSevice.Get((Guid)topic.ProductPost_Id);
            }

            var model = new ProductViewModel
            {
                Cat     = cat,
                product = topic,
                post    = post
            };

            return(View(model));
        }
示例#2
0
        public void UpdateProductDetails()
        {
            if (!ValidateProductDetails())
            {
                return;
            }

            string barcode = m_UIControl.tf_ProductDetails_Barcode.Text.Trim();

            if (CheckIfBarcodeAlreadyInUse(barcode))
            {
                m_UIControl.lbl_Error.Text = "This Barcode is already in use!";
                return;
            }

            string name = m_UIControl.tf_ProductDetails_ProductName.Text.Trim();

            if (CheckIfProductNameAlreadyInUse(name))
            {
                m_UIControl.lbl_Error.Text = "This Name is already in use!";
                return;
            }

            ProductGet existingProduct = m_Product;

            ProductPost product = new ProductPost(existingProduct);

            product.ID             = int.Parse(m_UIControl.tf_ProductDetails_ProductID.Text.Trim());
            product.Barcode        = barcode;
            product.Name           = name;
            product.Description    = m_UIControl.tf_ProductDetails_Description.Text.Trim();
            product.Unit           = ProductUnit.GetUnitFromText(m_UIControl.cb_Unit.Text);
            product.RetailPrice    = int.Parse(m_UIControl.tf_ProductDetails_RetailPrice.Text.Trim());
            product.WholeSalePrice = int.Parse(m_UIControl.tf_ProductDetails_WholesalePrice.Text.Trim());
            product.Discount       = double.Parse(m_UIControl.tf_ProductDetails_Discount.Text.Trim());
            product.CGST           = double.Parse(m_UIControl.tf_ProductDetails_CGST.Text.Trim());
            product.SGST           = double.Parse(m_UIControl.tf_ProductDetails_SGST.Text.Trim());

            string categoryName = m_UIControl.cb_ProductDetails_Category.Text.Trim();

            product.CategoryID = DataService.GetCategoryDataController().GetByName(categoryName).ID;

            bool imageModified = false;

            if (m_UIControl.pictureBox_ProductImage.Tag != null)
            {
                product.ImagePath = m_UIControl.pictureBox_ProductImage.Tag.ToString();
                imageModified     = true;
            }

            m_Product = DataService.GetProductDataController().Put(product, imageModified);
            string message = (m_Product == null) ? "Failed to Update Product Details!" : "Product Details updated successfully!";

            MessageBox.Show(m_UIControl, message);

            // fire entry updated event
            Event_EntryUpdated e = new Event_EntryUpdated(DBEntityType.PRODUCT, m_Product.ID);

            EventBroadcaster.Get().BroadcastEvent(e);
        }
 public ResultDto InsertProduct(ProductPost post)
 {
     ResultDto result = new ResultDto();
     //判断该产品是否已添加
     var builder = Builders<ProductMongo>.Filter;
     var filter = builder.Eq(x => x.Name, post.name);
     filter &= builder.Eq(x => x.IsDel, false);
     var col = MongoDBHelper.Instance.GetProduct();
     try
     {
         var query = col.Find(filter).FirstOrDefault();
         if (query != null)
         {
             result.Message = "该产品已存在!";
             return result;
         }
         var product = new ProductMongo
         {
             Name = post.name,
             Description = post.description,
             Price = post.price,
             CreatedAt = DateTime.Now.AddHours(8),
         };
         col.InsertOne(product);
         result.IsSuccess = true;
         return result;
     }
     catch (Exception ex)
     {
         result.Message = ex.Message;
         return result;
     }
 }
示例#4
0
        public void Update(ProductPost post)
        {
            post.DateEdited = DateTime.UtcNow;

            var Cmd = _context.CreateCommand();

            Cmd.CommandText = "UPDATE [ProductPost] SET [PostContent] = @PostContent, [DateCreated] = @DateCreated, [VoteCount] = @VoteCount, [DateEdited] = @DateEdited, [IsSolution] = @IsSolution, [IsTopicStarter] = @IsTopicStarter,"
                              + " [FlaggedAsSpam] = @FlaggedAsSpam, [IpAddress] = @IpAddress, [Pending] = @Pending, [SearchField] = @SearchField, [InReplyTo] = @InReplyTo, [Product_Id] = @Product_Id, [MembershipUser_Id] = @MembershipUser_Id "
                              + " WHERE [Id] = @Id";

            Cmd.AddParameters("Id", post.Id);
            Cmd.AddParameters("PostContent", post.PostContent);
            Cmd.AddParameters("DateCreated", post.DateCreated);
            Cmd.AddParameters("VoteCount", post.VoteCount);
            Cmd.AddParameters("DateEdited", post.DateEdited);
            Cmd.AddParameters("IsSolution", post.IsSolution);
            Cmd.AddParameters("IsTopicStarter", post.IsTopicStarter);
            Cmd.AddParameters("FlaggedAsSpam", post.FlaggedAsSpam);
            Cmd.AddParameters("IpAddress", post.IpAddress);
            Cmd.AddParameters("Pending", post.Pending);
            Cmd.AddParameters("SearchField", post.SearchField);
            Cmd.AddParameters("InReplyTo", post.InReplyTo);
            Cmd.AddParameters("Product_Id", post.Product_Id);
            Cmd.AddParameters("MembershipUser_Id", post.MembershipUser_Id);

            bool ret = Cmd.command.ExecuteNonQuery() > 0;

            Cmd.cacheStartsWithToClear(CacheKeys.ProductPost.StartsWith);
            Cmd.Close();

            if (!ret)
            {
                throw new Exception("Update ProductPost false");
            }
        }
        public async Task <int> PostProduct(int userId, [FromBody] ProductPost postProduct)
        {
            var product = new Product
            {
                Name   = postProduct.name,
                UserID = userId
            };

            _context.Products.Add(product);
            await _context.SaveChangesAsync();

            foreach (var category in postProduct.categories)
            {
                var productCategory = new ProductCategory
                {
                    CategoryID = category,
                    ProductID  = product.ID
                };
                _context.ProductCategories.Add(productCategory);
            }
            await _context.SaveChangesAsync();


            return(product.ID);
        }
示例#6
0
        public HttpStatusCode Post([FromBody] ProductPost postedProduct)
        {
            var product = Mapper.MapRequestModelToModel(postedProduct);

            _productService.AddProduct(product);

            return(HttpStatusCode.OK);
        }
示例#7
0
        public void UpdateProduct(int userId, int id, ProductPost product)
        {
            var productObj = _context.Products.FirstOrDefault(p => p.ID == id && p.UserID == userId);

            productObj.Name = product.name;
            _context.SaveChanges();
            DeleteOldCategories(productObj, product.categories);
            AddNewCategories(productObj, product.categories);
        }
示例#8
0
        public string deletepost(int UserID)
        {
            ProductPost abc = ProductPostRepository.GetbyID(UserID);

            abc.status = 0;

            ProductPostRepository.Update(abc);
            return("成功");
        }
示例#9
0
        public ProductPreviewPopup(ProductPost product, byte[] image, NewProductPage page)
        {
            InitializeComponent();

            this.NewProduct     = product;
            this.productImage   = image;
            this.newProductPage = page;

            SetupProductFrame();
            SetupProductDetailsFrame();
        }
示例#10
0
        public async Task <IActionResult> AddProductTest([FromForm] ProductModel product)
        {
            string Url = "https://localhost:44374/api/Products/PostProduct";

            using (var client = new HttpClient())
            {
                //var a = Object;
                string Image = "";
                MultipartFormDataContent multiContent = new MultipartFormDataContent();

                using (var memoryStream = new MemoryStream())
                {
                    await product.Image.CopyToAsync(memoryStream);

                    var a = memoryStream.ToArray();
                    Image = Convert.ToBase64String(a);
                }
                var response = new HttpResponseMessage();

                //double price = Convert.ToDouble(product.Price);
                var PostProduct = new ProductPost();
                PostProduct.Description = product.Description;
                PostProduct.Group       = product.Group;
                PostProduct.Image       = Image;
                PostProduct.Name        = product.Name;
                PostProduct.Price       = product.Price;
                PostProduct.Quantity    = product.Quantity;
                PostProduct.Status      = product.Status;
                PostProduct.SubGroup    = product.SubGroup;
                PostProduct.Vat         = 15.00;
                PostProduct.Discount    = 0.00;
                PostProduct.DateCreated = DateTime.Now;

                var formDataContent = new MultipartFormDataContent();
                formDataContent.Add(new StringContent(PostProduct.Image), "Image");
                formDataContent.Add(new StringContent(PostProduct.Name), "name");
                formDataContent.Add(new StringContent(PostProduct.Description), "description");
                formDataContent.Add(new StringContent(PostProduct.Group), "group");
                formDataContent.Add(new StringContent(PostProduct.SubGroup), "subGroup");
                formDataContent.Add(new StringContent(PostProduct.Status), "status");
                formDataContent.Add(new StringContent(PostProduct.Price.ToString()), "price");
                formDataContent.Add(new StringContent(PostProduct.Quantity), "quantity");
                formDataContent.Add(new StringContent(PostProduct.Vat.ToString()), "vat");
                formDataContent.Add(new StringContent(PostProduct.Discount.ToString()), "discount");
                formDataContent.Add(new StringContent(PostProduct.DateCreated.ToString()), "datecreated");

                response = await client.PostAsync("https://localhost:44374/api/Products/PostProduct", formDataContent);

                var data = await response.Content.ReadAsStringAsync();

                response.EnsureSuccessStatusCode();
            }
            return(RedirectToAction(nameof(Index)));
        }
示例#11
0
        public void Del(ProductPost post)
        {
            var Cmd = _context.CreateCommand();

            Cmd.CommandText = "DELETE FROM [ProductPost] WHERE Id = @Id";

            Cmd.AddParameters("Id", post.Id);

            Cmd.command.ExecuteNonQuery();
            Cmd.cacheStartsWithToClear(CacheKeys.ProductPost.StartsWith);
            Cmd.Close();
        }
示例#12
0
        public NewProductPage()
        {
            InitializeComponent();

            NavigationPage.SetHasNavigationBar(this, false);

            _newProduct = new ProductPost();

            _defaultDate              = DateTime.Now;
            _newProduct.ExpireAt      = _defaultDate;
            pkrExpireDate.MinimumDate = _defaultDate;
        }
示例#13
0
        public void Del(ProductPost post)
        {
            var Cmd = _context.CreateCommand();

            Cmd.CommandText = "DELETE FROM [ProductPost] WHERE Id = @Id";

            Cmd.Parameters.Add("Id", SqlDbType.UniqueIdentifier).Value = post.Id;

            Cmd.command.ExecuteNonQuery();
            Cmd.cacheStartsWithToClear(CacheKeys.ProductPost.StartsWith);
            Cmd.Close();
        }
示例#14
0
        public async Task <int> AddProductAsync(ProductPost dto)
        {
            var im = new Product()
            {
                CategoryID  = dto.CategoryID,
                Description = dto.Description,
                Price       = dto.Price,
                Stock       = dto.Stock
            };
            var om = await _dal.AddProductAsync(im);

            return(om);
        }
        public async Task <IActionResult> AddProduct([FromForm] ProductModel product, CancellationToken cancellationToken)
        {
            string Url = "https://localhost:44377/api/Products/PostProduct";

            using (var client = new HttpClient())
            {
                //var a = Object;
                string Image = "";
                MultipartFormDataContent multiContent = new MultipartFormDataContent();

                using (var memoryStream = new MemoryStream())
                {
                    await product.Image.CopyToAsync(memoryStream);

                    var a = memoryStream.ToArray();
                    Image = Convert.ToBase64String(a);
                }
                var response = new HttpResponseMessage();

                var PostProduct = new ProductPost
                {
                    Id          = product.Id,
                    Description = product.Description,
                    Group       = product.Group,
                    Image       = Image,
                    Name        = product.Name,
                    Price       = product.Price,
                    Quantity    = product.Quantity,
                    Status      = product.Status,
                    SubGroup    = product.SubGroup,
                    Vat         = 15.00
                };

                var formDataContent = new MultipartFormDataContent();
                formDataContent.Add(new StringContent(PostProduct.Image), "image");
                formDataContent.Add(new StringContent(PostProduct.Name), "name");
                formDataContent.Add(new StringContent(PostProduct.Description), "description");
                formDataContent.Add(new StringContent(PostProduct.Group), "group");
                formDataContent.Add(new StringContent(PostProduct.SubGroup), "subGroup");
                formDataContent.Add(new StringContent(PostProduct.Status), "status");
                formDataContent.Add(new StringContent(PostProduct.Price), "price");
                formDataContent.Add(new StringContent(PostProduct.Quantity), "quantity");

                response = await client.PostAsync(Url.ToString(), formDataContent);

                var data = await response.Content.ReadAsStringAsync();

                response.EnsureSuccessStatusCode();
            }
            return(RedirectToAction(nameof(Index)));
        }
        public async Task <Product> Insert(ProductPost productPost)
        {
            var brand = await _brands.GetById(productPost.BrandId);

            if (brand == null)
            {
                throw new Exception("FABRICANTE não encontrado.");
            }

            var product = productPost.CreateDomain(brand);

            await _products.Insert(product);

            return(product);
        }
示例#17
0
        //Mapper from the RestApi Layer to the Service Layer
        public static Service.Model.Product MapRequestModelToModel(ProductPost postedProduct)
        {
            if (postedProduct == null)
            {
                return(null);
            }

            return(new Service.Model.Product()
            {
                Id = postedProduct.Id,
                Description = postedProduct.Description,
                Name = postedProduct.Name,
                Price = postedProduct.Price,
                Is4G = postedProduct.Is4G,
                Weight = postedProduct.Weight
            });
        }
示例#18
0
        public string commemtProductPost(ProductCommentListViewModel ps)
        {
            try
            {
                ProductPost product = new ProductPost()
                {
                    //ProductPostID = ps.ProductPostID,
                    productName = ps.productName,
                    productDescription = ps.productDescription,
                    status = ps.status==null?1:ps.status,
                    inStoreQTY = ps.inStoreQTY,
                    price = ps.price,
                    TagID = ps.TagID,
                    RequiredPostID = ps.RequiredPostID,
                   
                    createdTime = DateTime.Now,
                    county = ps.county,
                    district = ps.district,
                    UserID = Convert.ToInt32(Request.Cookies["LoginAccount"].Value)

                };
                if (ps.upphoto == null)
                {
                    product.productImg = "無圖示.jpg";
                }
                else
                {
                   

                    product.productImg = ps.upphoto.FileName;
                    string filename = ps.upphoto.FileName;
                    ps.upphoto.SaveAs(Server.MapPath("../Content/ProductPostImg/") + filename);
                    string filePath = $"../Content/ProductPostImg/{filename}";

                }
                //HttpPostedFileBase photo = new HttpPostedFileBase(upphoto);

                productPostRepository.Create(product);

                return "留言成功";
            }
            catch (Exception e) {
                return e.Message;
            }
        }
 public ResultDto UpdateProduct(ProductPost post)
 {
     ResultDto result = new ResultDto();
     var builder = Builders<ProductMongo>.Filter;
     var filter = builder.Eq(x => x._id, new ObjectId(post.id));
     filter &=builder.Eq(x => x.IsDel, false);
     var col = MongoDBHelper.Instance.GetProduct();
     try
     {
         var update = new UpdateDocument { { "$set", new QueryDocument { { "Name", post.name }, { "Description", post.description }, { "Price", post.price } } } };
         col.UpdateOne(filter, update);
         result.IsSuccess = true;
         return result;
     }
     catch (Exception ex)
     {
         result.Message = ex.Message;
         return result;
     }
 }
        public ProductGet Post(ProductPost post)
        {
            var productDTO = new ProductDTO(post);

            m_Context.Products.Add(productDTO);
            m_Context.SaveChanges();

            string pathToSave = SaveImage(productDTO);

            productDTO.ImagePath = pathToSave;

            m_Context.Entry(productDTO).State = EntityState.Modified;
            m_Context.SaveChanges();

            if (productDTO == null)
            {
                return(null);
            }

            return(new ProductGet(m_Context, productDTO));
        }
        public ProductGet Put(ProductPost post, bool imageModified = true)
        {
            var productDTO = m_Context.GetProduct(post.ID);

            if (productDTO == null)
            {
                return(null);
            }

            productDTO.CopyFrom(post);

            string pathToSave = SaveImage(productDTO, imageModified);

            productDTO.ImagePath = pathToSave;

            m_Context.Entry(productDTO).State = EntityState.Modified;

            m_Context.SaveChanges();

            return(new ProductGet(m_Context, productDTO));
        }
示例#22
0
        private ProductPost DataRowToProductPost(DataRow data)
        {
            if (data == null)
            {
                return(null);
            }

            ProductPost post = new ProductPost();

            post.Id          = new Guid(data["Id"].ToString());
            post.PostContent = data["PostContent"].ToString();
            post.DateCreated = (DateTime)data["DateCreated"];
            post.VoteCount   = (int)data["VoteCount"];
            post.DateEdited  = (DateTime)data["DateEdited"];
            post.IsSolution  = (bool)data["IsSolution"];
            if (!data["IsTopicStarter"].ToString().IsNullEmpty())
            {
                post.IsTopicStarter = (bool)data["IsTopicStarter"];
            }
            if (!data["FlaggedAsSpam"].ToString().IsNullEmpty())
            {
                post.FlaggedAsSpam = (bool)data["FlaggedAsSpam"];
            }
            post.IpAddress = data["IpAddress"].ToString();
            if (!data["Pending"].ToString().IsNullEmpty())
            {
                post.Pending = (bool)data["Pending"];
            }
            post.SearchField = data["SearchField"].ToString();
            if (!data["InReplyTo"].ToString().IsNullEmpty())
            {
                post.InReplyTo = new Guid(data["InReplyTo"].ToString());
            }
            post.Product_Id        = new Guid(data["Product_Id"].ToString());
            post.MembershipUser_Id = new Guid(data["MembershipUser_Id"].ToString());


            return(post);
        }
示例#23
0
        public void Add(ProductPost post)
        {
            post.DateCreated = DateTime.UtcNow;
            post.DateEdited  = post.DateCreated;

            var Cmd = _context.CreateCommand();


            Cmd.CommandText  = "IF NOT EXISTS (SELECT * FROM [ProductPost] WHERE [Id] = @Id)";
            Cmd.CommandText += " BEGIN INSERT INTO [ProductPost]([Id],[PostContent],[DateCreated],[VoteCount],[DateEdited],[IsSolution],[IsTopicStarter],[FlaggedAsSpam],[IpAddress],[Pending],[SearchField],[InReplyTo],[Product_Id],[MembershipUser_Id])";
            Cmd.CommandText += " VALUES(@Id,@PostContent,@DateCreated,@VoteCount,@DateEdited,@IsSolution,@IsTopicStarter,@FlaggedAsSpam,@IpAddress,@Pending,@SearchField,@InReplyTo,@Product_Id,@MembershipUser_Id) END ";

            Cmd.AddParameters("Id", post.Id);
            Cmd.AddParameters("PostContent", post.PostContent);
            Cmd.AddParameters("DateCreated", post.DateCreated);
            Cmd.AddParameters("VoteCount", post.VoteCount);
            Cmd.AddParameters("DateEdited", post.DateEdited);
            Cmd.AddParameters("IsSolution", post.IsSolution);
            Cmd.AddParameters("IsTopicStarter", post.IsTopicStarter);
            Cmd.AddParameters("FlaggedAsSpam", post.FlaggedAsSpam);
            Cmd.AddParameters("IpAddress", post.IpAddress);
            Cmd.AddParameters("Pending", post.Pending);
            Cmd.AddParameters("SearchField", post.SearchField);
            Cmd.AddParameters("InReplyTo", post.InReplyTo);
            Cmd.AddParameters("Product_Id", post.Product_Id);
            Cmd.AddParameters("MembershipUser_Id", post.MembershipUser_Id);

            bool ret = Cmd.command.ExecuteNonQuery() > 0;

            Cmd.cacheStartsWithToClear(CacheKeys.ProductPost.StartsWith);
            Cmd.Close();

            if (!ret)
            {
                throw new Exception("Add ProductPost false");
            }
        }
示例#24
0
        public async Task <IActionResult> Post(ProductPost productPost)
        {
            Product product = await _productService.Insert(productPost);

            return(Ok(new Response <long>(product.Id)));
        }
示例#25
0
        public static async Task <Product> PostProductAsync(ProductPost product, ByteArrayPart bytes)
        {
            var restService = new Tech4GamingApi();

            return(await restService.PostProductAsync(product, bytes));
        }
示例#26
0
        public async Task <IActionResult> PutProduct([FromRoute] int userId, [FromRoute] int id, [FromBody] ProductPost product)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _productHelper.UpdateProduct(userId, id, product);

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
示例#27
0
        public ActionResult EditProduct(AdminEditProductViewModel model)
        {
            var cats = _categoryService.GetAllowedEditCategories(UsersRole, true);

            model.Categories = _categoryService.GetBaseSelectListCategories(cats);
            bool getval = false;

            if (ModelState.IsValid)
            {
                if (model.Content == null)
                {
                    model.Content = string.Empty;
                }

                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    try
                    {
                        var product = _productSevice.Get(model.Id);
                        if (product == null)
                        {
                            return(RedirectToAction("index"));
                        }

                        ProductPost post;
                        if (product.ProductPost_Id != null)
                        {
                            post = _productPostSevice.Get((Guid)product.ProductPost_Id);
                            //model.Content = post.PostContent;
                        }
                        else
                        {
                            post                   = new ProductPost();
                            post.Product_Id        = product.Id;
                            product.ProductPost_Id = post.Id;
                        }

                        product.Name              = model.Name;
                        product.Category_Id       = model.Category;
                        product.Image             = model.Image;
                        product.IsLocked          = model.IsLocked;
                        product.ProductClassId    = model.ProductClass;
                        product.MembershipUser_Id = LoggedOnReadOnlyUser.Id;
                        post.PostContent          = model.Content;

                        product.ShotContent       = string.Concat(StringUtils.ReturnAmountWordsFromString(StringUtils.StripHtmlFromString(post.PostContent), 50), "....");
                        product.isAutoShotContent = true;
                        var i = product.ShotContent.Length;
                        if (i > 450)
                        {
                            product.ShotContent = product.ShotContent.Substring(0, 440) + "...";
                        }


                        if (model.AllAttribute != null)
                        {
                            foreach (var it in model.AllAttribute)
                            {
                                var a = _productSevice.GetAttribute(it.AttriId);
                                it.Name      = a.LangName;
                                it.ValueType = a.ValueType;
                                it.IsNull    = a.IsNull;

                                if (!a.ValueOption.IsNullEmpty() && a.ValueType == 2)
                                {
                                    dynamic json = JsonConvert.DeserializeObject(a.ValueOption);
                                    if (json != null)
                                    {
                                        it.ValueOptions = new List <string>();
                                        foreach (var itt in json)
                                        {
                                            it.ValueOptions.Add((string)itt);
                                        }
                                    }
                                }

                                //if (!a.ValueFindter.IsNullEmpty())
                                //{
                                //	dynamic json = JsonConvert.DeserializeObject(a.ValueFindter);
                                //	if (json != null)
                                //	{
                                //		it.FindterNums = new List<AdminAttributeNumberFindter>();
                                //		foreach (dynamic itt in json)
                                //		{
                                //			it.FindterNums.Add(new AdminAttributeNumberFindter { Name = (string)itt.Name });
                                //		}
                                //	}
                                //}

                                _productSevice.Set(product, a, it.Value);
                            }
                        }
                        getval = true;


                        _productPostSevice.Update(post);
                        _productSevice.Update(product);

                        unitOfWork.Commit();
                        // We use temp data because we are doing a redirect
                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message     = "Cập nhật sản phẩm thành công!",
                            MessageType = GenericMessages.success
                        };

                        //return RedirectToAction("Product", new { id = model.ProductClass });
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        ModelState.AddModelError("", "Xảy ra lỗi khi cập nhật sản phẩm");

                        if (!getval)
                        {
                            foreach (var it in model.AllAttribute)
                            {
                                var a = _productSevice.GetAttribute(it.AttriId);
                                it.Name      = a.LangName;
                                it.ValueType = a.ValueType;
                                it.IsNull    = a.IsNull;
                            }
                        }
                    }
                }
            }


            return(View(model));
        }
        public bool AddNewProduct()
        {
            var UI = m_UIControl;

            UI.DialogResult = DialogResult.None;

            UI.lbl_Error.Text = string.Empty;
            if (!ValidateProductDetails())
            {
                return(false);
            }

            string      categoryName = UI.cb_Category.Text.Trim();
            CategoryGet category     = DataService.GetCategoryDataController().GetByName(categoryName);

            int unit = UI.cb_Unit.SelectedIndex + 1;

            ProductPost productPost = new ProductPost();

            productPost.Name           = UI.tb_Name.Text.Trim();
            productPost.Barcode        = UI.tb_Barcode.Text.Trim();
            productPost.Description    = UI.tb_Description.Text.Trim();
            productPost.Unit           = unit;
            productPost.RetailPrice    = int.Parse(UI.tb_RetailPrice.Text.Trim());
            productPost.WholeSalePrice = int.Parse(UI.tb_WholeSalePrice.Text.Trim());
            productPost.CategoryID     = category.ID;
            productPost.CGST           = double.Parse(UI.tb_CGST.Text.Trim());
            productPost.SGST           = double.Parse(UI.tb_CGST.Text.Trim());
            productPost.Discount       = double.Parse(UI.tb_SGST.Text.Trim());

            productPost.ImagePath = GetImagePath();

            m_Product = DataService.GetProductDataController().Post(productPost);
            if (m_Product == null)
            {
                MessageBox.Show(UI, "Failed to Add Product!");
                return(false);
            }

            // post the Default details
            StockPost stock = new StockPost();

            stock.ProductID         = m_Product.ID;
            stock.AvailableQuantity = 0;
            stock.TotalQuantity     = 0;
            var stockPost = DataService.GetStockDataController().Post(stock);

            if (stockPost == null)
            {
                MessageBox.Show(UI, "Failed to Add Stock!");
                return(false);
            }

            // Broadcast NewProductAdded Event
            Event_NewEntryAdded e = new Event_NewEntryAdded(DBEntityType.PRODUCT, m_Product.ID);

            EventBroadcaster.Get().BroadcastEvent(e);

            MessageBox.Show(UI, "Product Added Successfully!");

            if (!m_UIControl.checkBox_AddAnotherProduct.Checked)
            {
                UI.DialogResult = DialogResult.OK;
                UI.Close();
            }

            return(true);
        }
示例#29
0
        public ActionResult EditProduct(AdminEditProductViewModel model)
        {
            var cats = _categoryService.GetAllowedEditCategories(UsersRole, true);

            model.Categories = _categoryService.GetBaseSelectListCategories(cats);
            bool getval = false;

            if (ModelState.IsValid)
            {
                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    try
                    {
                        var product = _productSevice.Get(model.Id);
                        if (product == null)
                        {
                            return(RedirectToAction("index"));
                        }

                        ProductPost post;
                        if (product.ProductPost_Id != null)
                        {
                            post = _productPostSevice.Get((Guid)product.ProductPost_Id);
                            //model.Content = post.PostContent;
                        }
                        else
                        {
                            post                   = new ProductPost();
                            post.Product_Id        = product.Id;
                            product.ProductPost_Id = post.Id;
                        }

                        model.Image = product.Image;

                        if (model.Files != null)
                        {
                            // Before we save anything, check the user already has an upload folder and if not create one
                            var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(SiteConstants.Instance.UploadFolderPath, product.Id));
                            if (!Directory.Exists(uploadFolderPath))
                            {
                                Directory.CreateDirectory(uploadFolderPath);
                            }

                            // Loop through each file and get the file info and save to the users folder and Db
                            var file = model.Files[0];
                            if (file != null)
                            {
                                // If successful then upload the file
                                var uploadResult = AppHelpers.UploadFile(file, uploadFolderPath, LocalizationService, true);

                                if (!uploadResult.UploadSuccessful)
                                {
                                    TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                    {
                                        Message     = uploadResult.ErrorMessage,
                                        MessageType = GenericMessages.danger
                                    };
                                    return(View(model));
                                }

                                // Save avatar to user
                                model.Image = uploadResult.UploadedFileName;
                            }
                        }

                        product.Name              = model.Name;
                        product.Category_Id       = model.Category;
                        product.Image             = model.Image;
                        product.IsLocked          = model.IsLocked;
                        product.ProductClassId    = model.ProductClass;
                        product.MembershipUser_Id = LoggedOnReadOnlyUser.Id;
                        post.PostContent          = model.Content;

                        product.ShotContent       = string.Concat(StringUtils.ReturnAmountWordsFromString(StringUtils.StripHtmlFromString(post.PostContent), 50), "....");
                        product.isAutoShotContent = true;

                        foreach (var it in model.AllAttribute)
                        {
                            var a = _productSevice.GetAttribute(it.AttriId);
                            it.Name      = a.LangName;
                            it.ValueType = a.ValueType;
                            it.IsNull    = a.IsNull;

                            _productSevice.Set(product, a, it.Value);
                        }
                        getval = true;


                        _productPostSevice.Update(post);
                        _productSevice.Update(product);

                        unitOfWork.Commit();
                        // We use temp data because we are doing a redirect
                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message     = "Cập nhật sản phẩm thành công!",
                            MessageType = GenericMessages.success
                        };

                        //return RedirectToAction("Product", new { id = model.ProductClass });
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        ModelState.AddModelError("", "Xảy ra lỗi khi cập nhật sản phẩm");

                        if (!getval)
                        {
                            foreach (var it in model.AllAttribute)
                            {
                                var a = _productSevice.GetAttribute(it.AttriId);
                                it.Name      = a.LangName;
                                it.ValueType = a.ValueType;
                                it.IsNull    = a.IsNull;
                            }
                        }
                    }
                }
            }


            return(View(model));
        }
        public OperationResult <ProductPostDTO> Add(ProductPost newProduct)
        {
            var sqlServerProductRepository = _sqlUnitOfWork.GetRepository <IProductSQLServerRepository>();
            var sqlServerClientRepository  = _sqlUnitOfWork.GetRepository <IClientSQLServerRepository>();
            var mongoProductRepository     = _mongoUnitOfWork.GetRepository <IProductMongoRepository>();

            var clientResult  = sqlServerClientRepository.Get(client => client.Id.Equals(newProduct.ClientId));
            var client        = clientResult.Data.FirstOrDefault();
            var isClientExist = client != null;
            var result        = new OperationResult <ProductPostDTO>();

            if (isClientExist)
            {
                newProduct.Tags?.Add(client.Name);
                var bsonId           = ObjectId.GenerateNewId();
                var sqlServerProduct = _mapper.Map <Product>(newProduct);
                var mongoProduct     = _mapper.Map <DAL.Models.Mongo.Product>(newProduct);
                var elasticProduct   = _mapper.Map <DAL.Models.ElasticSearch.Product>(newProduct);

                mongoProduct.ClientName = client.Name;
                mongoProduct.ClientId   = client.Id;
                mongoProduct.Id         = bsonId;

                var mongoResult = mongoProductRepository.Add(mongoProduct);
                result.Errors = mongoResult.Errors;
                result.Type   = mongoResult.Type;

                if (mongoResult.IsSuccess)
                {
                    sqlServerProduct.Id     = Guid.NewGuid();
                    sqlServerProduct.BsonId = bsonId.ToString();

                    var sqlServerResult = sqlServerProductRepository.Add(sqlServerProduct);
                    result.Errors = sqlServerResult.Errors;
                    result.Type   = sqlServerResult.Type;

                    if (sqlServerResult.IsSuccess)
                    {
                        elasticProduct.Id = bsonId.ToString();

                        var elasticResult = _productElasticSearchRepository.Add(elasticProduct);
                        result.Errors = elasticResult.Errors;
                        result.Type   = elasticResult.Type;

                        if (elasticResult.IsSuccess)
                        {
                            result.Type = ResultType.Success;
                            result.Data = new ProductPostDTO
                            {
                                Id   = bsonId.ToString(),
                                Name = mongoProduct.Name
                            };
                            _sqlUnitOfWork.Save();
                        }
                    }
                }
            }
            else
            {
                result.Type = ResultType.BadRequest;
                result.Errors.Add("Not valid client id");
            }

            return(result);
        }