Beispiel #1
0
        public Product AddProduct(ProductAddViewModel productAdd)
        {
            //MessageBox.Show(Environment.CurrentDirectory);
            Product product = new Product
            {
                Name       = productAdd.Name,
                CategoryId = productAdd.CategoryId,
                Price      = productAdd.Price,
                Quantity   = productAdd.Quantity,
                DateCreate = DateTime.Now
            };

            _productRepository.Add(product);
            _productRepository.SaveChanges();
            if (productAdd.Images.Count > 0)
            {
                List <string> imgTemp = new List <string>();
                foreach (var p in productAdd.Images)
                {
                    string fSaveName       = Guid.NewGuid().ToString() + ".jpg"; //Path.GetFileName(p.Source);
                    string fImages         = Environment.CurrentDirectory + ConfigurationManager.AppSettings["ImageStore"].ToString();
                    string fSaveImageBig   = "o_" + fSaveName;
                    string fSaveImageSmall = "s_" + fSaveName;
                    // Will not overwrite if the destination file already exists.
                    try
                    {
                        File.Copy(p.SourceOriginal, Path.Combine(fImages, fSaveImageBig));
                        imgTemp.Add(fSaveImageBig);
                        using (FileStream stream =
                                   new FileStream(Path.Combine(fImages, fSaveImageSmall),
                                                  FileMode.Create))
                        {
                            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                            encoder.Frames.Add(p.ImageFrame);
                            encoder.Save(stream);
                            imgTemp.Add(fSaveImageSmall);
                        }

                        ProductImage image = new ProductImage // сохраняем в таблицу ProductImages
                        {
                            Name      = fSaveName,            // сохраняем имя без приставки
                            ProductId = product.Id
                        };
                        _productImageRepository.Add(image);
                        // Catch exception if the file was already copied.
                    }
                    catch (IOException copyError)
                    {
                        MessageBox.Show(copyError.Message);
                        foreach (var item in imgTemp)
                        {
                            File.Delete(Path.Combine(fImages, item));
                        }
                        return(null);
                    }
                }
                _productImageRepository.SaveChanges();
            }
            return(product);
        }