Ejemplo n.º 1
0
        public void SaveAppendsExtensionBasedOnFormatWhenForceExtensionIsSet()
        {
            // Arrange
            // Use rooted path so we by pass using HttpContext
            var specifiedOutputFile = @"x:\some-dir\foo";
            string actualOutputFile = null;
            Action<string, byte[]> saveAction = (fileName, content) => { actualOutputFile = fileName; };

            // Act
            WebImage image = new WebImage(_BmpImageBytes);
            image.Save(GetContext(), saveAction, filePath: specifiedOutputFile, imageFormat: "jpg", forceWellKnownExtension: true);

            // Assert
            Assert.Equal(".jpeg", Path.GetExtension(actualOutputFile));
        }
Ejemplo n.º 2
0
        public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file)
        {
            //Проверяем модель на валидность
            if (!ModelState.IsValid)
            {
                using (Db db = new Db())
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    return(View(model));
                }
            }
            //Проверяем продукт на уникальность
            using (Db db = new Db())
            {
                if (db.Products.Any(x => x.Name == model.Name))
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    ModelState.AddModelError("", "Данный продукт уже создан!");
                    return(View(model));
                }
            }
            //Объявляем переменную ProductId
            int id;

            //Инициализируем и сохранчемм модель на основе ProductDTO
            using (Db db = new Db())
            {
                ProductDTO product = new ProductDTO();
                product.Name        = model.Name;
                product.Slug        = model.Name.Replace(" ", "-").ToLower();
                product.Description = model.Description;
                product.Color       = model.Color;
                product.Memory      = model.Memory;
                product.Price       = model.Price;
                product.CategoryId  = model.CategoryId;

                CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                product.CategoryName = catDTO.Name;

                db.Products.Add(product);
                db.SaveChanges();

                id = product.Id;
            }

            //Добавляем сообщение в TempData
            TempData["SM"] = "Продукт добавлен!";

            //работа с загрузкой изображения
            #region UploadImage
            // Создаем необходимые ссылки на дериктории
            var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads"));
            var pathString1       = Path.Combine(originalDirectory.ToString(), "Products");
            var pathString2       = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
            var pathString3       = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");
            var pathString4       = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery");
            var pathString5       = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs");

            //Проверяем наличие дириктории
            if (!Directory.Exists(pathString1))
            {
                Directory.CreateDirectory(pathString1);
            }

            if (!Directory.Exists(pathString2))
            {
                Directory.CreateDirectory(pathString2);
            }

            if (!Directory.Exists(pathString3))
            {
                Directory.CreateDirectory(pathString3);
            }

            if (!Directory.Exists(pathString4))
            {
                Directory.CreateDirectory(pathString4);
            }

            if (!Directory.Exists(pathString5))
            {
                Directory.CreateDirectory(pathString5);
            }

            //Проверяем загружен ли файл
            if (file != null && file.ContentLength > 0)
            {
                //Получаем расширение файла
                string ext = file.ContentType.ToLower();
                //Проверяем расширение

                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Db db = new Db())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "Изображение не было загружено - не верный формат файла!");
                        return(View(model));
                    }
                }
                //Объявляем переменную с имененем изображения
                string imageName = file.FileName;

                //Сохраняем имя изображения в модель DTO
                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;

                    db.SaveChanges();
                }
                //Назначаем пути к оригинальному и уменьшиному изображению
                var path  = string.Format($"{pathString2}\\{imageName}");
                var path2 = string.Format($"{pathString3}\\{imageName}");

                //Сохраняем оригинальное изображение
                file.SaveAs(path);

                //Создаем и сохраняем уменьшиную копию
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200).Crop(1, 1);
                img.Save(path2);
            }

            #endregion

            //Переадрисовываем пользователя
            return(RedirectToAction("AddProduct"));
        }
Ejemplo n.º 3
0
        public ActionResult AddProduct(ProductViewModel productViewModel, HttpPostedFileBase file)
        {
            if (!ModelState.IsValid)
            {
                List <DanhMuc> list = db.DanhMucs.ToList();
                ViewBag.listDanhMuc = new SelectList(list, "MaDanhMuc", "Ten");
                return(View(productViewModel));
            }

            if (db.SanPhams.Any(x => x.Ten == productViewModel.Ten))
            {
                //List<DanhMuc> list = db.DanhMucs.ToList();
                //ViewBag.listDanhMuc = new SelectList(list, "MaDanhMuc", "Ten");
                ModelState.AddModelError("", "Tên sản phẩm đã tồn tại");
                return(View(productViewModel));
            }

            int id;

            SanPham sanPham = new SanPham();

            sanPham.Ten        = productViewModel.Ten;
            sanPham.Slug       = productViewModel.Slug;
            sanPham.MoTa       = productViewModel.MoTa;
            sanPham.Gia        = productViewModel.Gia;
            sanPham.SoLuongTon = productViewModel.SoLuongTon;
            sanPham.Available  = productViewModel.Available;
            sanPham.MaDanhMuc  = productViewModel.MaDanhMuc;

            db.SanPhams.Add(sanPham);
            db.SaveChanges();

            id = sanPham.MaSanPham;

            TempData["Message"] = "Sản phẩm thêm thành công";

            #region upload image

            //create directories
            var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

            var pathstring1 = Path.Combine(originalDirectory.ToString(), "SanPhams");
            var pathstring2 = Path.Combine(originalDirectory.ToString(), "SanPhams" + id.ToString());
            var pathstring3 = Path.Combine(originalDirectory.ToString(), "SanPhams" + id.ToString() + "\\Thumbs");
            var pathstring4 = Path.Combine(originalDirectory.ToString(), "SanPhams" + id.ToString() + "\\Gallery");
            var pathstring5 = Path.Combine(originalDirectory.ToString(), "SanPhams" + id.ToString() + "\\Gallery\\Thumbs");

            if (!Directory.Exists(pathstring1))
            {
                Directory.CreateDirectory(pathstring1);
            }
            if (!Directory.Exists(pathstring2))
            {
                Directory.CreateDirectory(pathstring2);
            }
            if (!Directory.Exists(pathstring3))
            {
                Directory.CreateDirectory(pathstring3);
            }
            if (!Directory.Exists(pathstring4))
            {
                Directory.CreateDirectory(pathstring4);
            }
            if (!Directory.Exists(pathstring5))
            {
                Directory.CreateDirectory(pathstring5);
            }

            if (file != null && file.ContentLength > 0)
            {
                string ext = file.ContentType.ToLower();

                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    ModelState.AddModelError("", "Hình ảnh upload không thành công");
                    return(View(productViewModel));
                }
                string imagename = file.FileName;

                sanPham      = db.SanPhams.Find(id);
                sanPham.Hinh = imagename;
                db.SaveChanges();

                var path  = string.Format("{0}\\{1}", pathstring2, imagename);
                var path2 = string.Format("{0}\\{1}", pathstring3, imagename);

                file.SaveAs(path);

                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }
            db.SaveChanges();
            #endregion
            return(RedirectToAction("AddProduct"));
        }
Ejemplo n.º 4
0
        public ActionResult Register([Bind(Include = "MerchantID,Email,MatKhauMaHoa,HoTen,DiaChi,GioiTinhID,TenCuaHang,SoDienThoai")] Merchant merchant, string AuthenticationCode, HttpPostedFileBase imageAvatar)
        {
            //check Ho ten
            if (merchant.HoTen.Trim().Any(char.IsNumber))
            {
                ViewBag.GioiTinhID = new SelectList(db.GioiTinhs, "GioiTinhID", "TenGioiTinh", "1");
                ModelState.AddModelError("", "Họ tên không hợp lệ!");
                return(View(merchant));
            }
            //check password
            if (merchant.MatKhauMaHoa.Trim().Length < 5)
            {
                ViewBag.GioiTinhID = new SelectList(db.GioiTinhs, "GioiTinhID", "TenGioiTinh", "1");
                ModelState.AddModelError("", "Mật khẩu không hợp lệ! Mật khẩu hợp lệ phải chứa ít nhất 5 ký tự bao gồm chữ và số");
                return(View(merchant));
            }
            if (merchant.MatKhauMaHoa.Trim().All(char.IsLetter))
            {
                ViewBag.GioiTinhID = new SelectList(db.GioiTinhs, "GioiTinhID", "TenGioiTinh", "1");
                ModelState.AddModelError("", "Mật khẩu không hợp lệ! Mật khẩu hợp lệ phải chứa ít nhất 1 ký tự số và chữ");
                return(View(merchant));
            }
            var authenticationEmail = (AuthenticationEmail)Session[CommonConstants.AUTHENTICATIONEMAILMERCHANT_SESSION];

            if (ModelState.IsValid & authenticationEmail != null)
            {
                if (merchant.Email == authenticationEmail.Email & authenticationEmail.AuthenticationCode == AuthenticationCode)
                {
                    merchant.MatKhauMaHoa = Encryptor.SHA256Encrypt(merchant.MatKhauMaHoa);
                    merchant.TrangThai    = false;
                    merchant.NgayTao      = System.DateTime.Now;
                    merchant.SoLuongKIPXu = 0;
                    db.Merchants.Add(merchant);
                    db.SaveChanges();

                    if (imageAvatar != null)
                    {
                        //Resize Image
                        WebImage img = new WebImage(imageAvatar.InputStream);
                        //img.Resize(500, 1000);

                        var    filePathOriginal = Server.MapPath("/Assets/Image/Merchant/");
                        var    fileName         = merchant.MerchantID + ".jpg";
                        string savedFileName    = Path.Combine(filePathOriginal, fileName);
                        img.Save(savedFileName);
                    }

                    Session[CommonConstants.USERMERCHANT_SESSION] = null;

                    return(RedirectToAction("MerchantRegSuccess", "Home", new { area = "" }));
                }
                else
                {
                    ViewBag.GioiTinhID = new SelectList(db.GioiTinhs, "GioiTinhID", "TenGioiTinh");
                    ModelState.AddModelError("", "Mã xác thực không hợp lệ");
                    return(View(merchant));
                }
            }
            ViewBag.GioiTinhID = new SelectList(db.GioiTinhs, "GioiTinhID", "TenGioiTinh", 1);
            return(View(merchant));
        }
Ejemplo n.º 5
0
        public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) //caters for uploaed image named file in AddProduct view
        {
            //check model state
            if (!ModelState.IsValid)
            {
                // populate categories property in the product model
                model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                return(View(model));
            }

            //Make sure product name is unique

            //check if its unique
            if (db.Products.Any(x => x.Name == model.Name))
            {
                //if there's a match
                model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                ModelState.AddModelError("", "That product name is taken");
                return(View(model));
            }

            //Declare Product id
            int id;

            //Init and save productDTO
            Product product = new Product();

            product.Name        = model.Name;
            product.Slug        = model.Name.Replace(" ", "-").ToLower();
            product.Description = model.Description;
            product.Price       = model.Price;
            product.CategoryId  = model.CategoryId;

            //Also need to get categories name  using the categoires DTO

            Category catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); //for categories selectList

            product.CategoryName = catDTO.Name;

            //add dto
            db.Products.Add(product);
            db.SaveChanges();

            //get id of primary key of row just inserted
            id = product.Id;


            //Set TempData message
            TempData["SM"] = "You have added a product!";

            #region Upload Image

            //code create necessary directories not done mannually
            var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));


            var pathString1 = Path.Combine(originalDirectory.ToString(), "Products");                                        //another folder
            var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());                      // creates another folder
            var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thubs");          //creates another folder for thubs
            var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery");        //creates another folder for gallery images
            var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thubs"); //creats another folder for gallery images

            if (!Directory.Exists(pathString1))
            {
                Directory.CreateDirectory(pathString1);
            }

            if (!Directory.Exists(pathString2))
            {
                Directory.CreateDirectory(pathString2);
            }

            if (!Directory.Exists(pathString3))
            {
                Directory.CreateDirectory(pathString3);
            }

            if (!Directory.Exists(pathString4))
            {
                Directory.CreateDirectory(pathString4);
            }

            if (!Directory.Exists(pathString5))
            {
                Directory.CreateDirectory(pathString5);
            }


            //Check if file was uploaded

            if (file != null && file.ContentLength > 0)
            {
                //Get file extensions
                string ext = file.ContentType.ToLower();
                //Verify extension
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjeg" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    ModelState.AddModelError("", "The image was not uploaded -wrong image extension");
                    return(View(model));
                }

                //Intitilase image name
                string imageName = file.FileName;

                //Save image name to DTO
                Product dto = db.Products.Find(id);
                dto.ImageName = imageName;
                db.SaveChanges();

                //Set original and thub image paths#
                var path  = string.Format("{0}\\{1}", pathString2, imageName);
                var path2 = string.Format("{0}\\{1}", pathString3, imageName);

                //save original image
                file.SaveAs(path);
                //create and save thub
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }

            #endregion

            //Redirect



            return(RedirectToAction("AddProduct"));
        }
Ejemplo n.º 6
0
        public void SaveUpdatesFileNameOfWebImageWhenFormatChanges()
        {
            // Arrange
            string imagePath = @"x:\images\foo.jpg";
            var context = GetContext();

            // Act
            WebImage image = new WebImage(context, _ => _JpgImageBytes, imagePath);

            image.Save(context, (_, __) => { }, imagePath, "png", forceWellKnownExtension: true);

            // Assert
            Assert.Equal(@"x:\images\foo.jpg.png", image.FileName);
        }
Ejemplo n.º 7
0
        public void SaveThrowsWhenPathIsEmpty()
        {
            Action<string, byte[]> saveAction = (path, content) => { };
            WebImage image = new WebImage(_BmpImageBytes);

            Assert.ThrowsArgumentNullOrEmptyString(
                () => image.Save(GetContext(), saveAction, filePath: String.Empty, imageFormat: null, forceWellKnownExtension: true),
                "filePath");
        }
Ejemplo n.º 8
0
        public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file)
        {
            //Получение id продукта
            int id = model.Id;

            //Заполнение списка ктегориями и изображениями
            using (Db db = new Db())
            {
                model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
            }

            model.GalleryImages = Directory
                                  .EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Small"))
                                  .Select(fn => Path.GetFileName(fn));

            //Проверка модели на валидность
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //Проверка имени продукта на уникальность
            using (Db db = new Db())
            {
                if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name))
                {
                    ModelState.AddModelError("", "Это название рекламы занято");
                    return(View(model));
                }
            }

            //Обновление продукта
            using (Db db = new Db())
            {
                ProductDTO dto = db.Products.Find(id);

                dto.Name        = model.Name;
                dto.Slug        = model.Name.Replace(" ", "-").ToLower();
                dto.Description = model.Description;
                dto.Price       = model.Price;
                dto.CategoryId  = model.CategoryId;
                dto.ImageName   = model.ImageName;

                CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);  //Присваивание текущей категории модели
                dto.CategoryName = catDTO.Name;

                db.SaveChanges();
            }

            //Установка сообщения в TempData
            TempData["M"] = "Вы изменили рекламу";

            //Логика обработки изображений
            #region Image Upload

            //Проверка загрузки файла
            if (file != null && file.ContentLength > 0)
            {
                //Получение расширения файла
                string ext = file.ContentType.ToLower();

                //Проверка расширения
                if (ext != "image/jpg" &&
                    ext != "image/png" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png")
                {
                    using (Db db = new Db())
                    {
                        ModelState.AddModelError("", "Картинка не загружена. Недопустимое расширение.");
                        return(View(model));
                    }
                }

                //Установка путей загрузки
                var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads"));

                var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
                var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Small");

                //Удаление существующих путей и директорий
                DirectoryInfo di1 = new DirectoryInfo(pathString1);
                DirectoryInfo di2 = new DirectoryInfo(pathString2);

                //удаление в основной директории
                foreach (var file2 in di1.GetFiles())
                {
                    file2.Delete();
                }

                //Удаление цменьшенных изображений
                foreach (var file3 in di1.GetFiles())
                {
                    file3.Delete();
                }

                //Сохранение имени изображения
                string imageName = file.FileName;

                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;

                    db.SaveChanges();
                }

                //Сохранение оригинала и уменьшенной версии
                var path  = string.Format($"{pathString1}\\{imageName}");  //к оригинальному изображению
                var path2 = string.Format($"{pathString2}\\{imageName}");  //к уменьшенному

                //Сохранение оригинального изображения
                file.SaveAs(path);

                //Создание и сохранение уменьшенной картинки
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200).Crop(1, 1);
                img.Save(path2);
            }
            #endregion

            //Переадресация пользователя
            return(RedirectToAction("EditProduct"));
        }
Ejemplo n.º 9
0
        public ActionResult ArizaBildirimi(ArizaViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            try
            {
                var arizaRepo = new ArizaRepository();
                var ariza     = new Ariza()
                {
                    MusteriId            = HttpContext.User.Identity.GetUserId(),
                    Aciklama             = model.Aciklama,
                    MarkaAdi             = model.MarkaAdi,
                    ModelAdi             = model.ModelAdi,
                    Adres                = model.Adres,
                    ArizaOlusturmaTarihi = DateTime.Now,
                };
                arizaRepo.Insert(ariza);
                if (model.PostedFile.Count > 0)
                {
                    model.PostedFile.ForEach(file =>
                    {
                        if (file != null && file.ContentLength > 0)
                        {
                            string fileName = Path.GetFileNameWithoutExtension(file.FileName);
                            string extName  = Path.GetExtension(file.FileName);
                            fileName        = StringHelpers.UrlFormatConverter(fileName);
                            fileName       += StringHelpers.GetCode();
                            var klasoryolu  = Server.MapPath("~/Upload/");
                            var dosyayolu   = Server.MapPath("~/Upload/") + fileName + extName;

                            if (!Directory.Exists(klasoryolu))
                            {
                                Directory.CreateDirectory(klasoryolu);
                            }
                            file.SaveAs(dosyayolu);

                            WebImage img = new WebImage(dosyayolu);
                            img.Resize(250, 250, false);
                            img.Save(dosyayolu);

                            new FotografRepository().Insert(new Fotograf()
                            {
                                ArizaId = ariza.Id,
                                Yol     = "/Upload/" + fileName + extName
                            });
                        }
                    });
                }
                var fotograflar = new FotografRepository().GetAll(x => x.ArizaId == ariza.Id).ToList();
                ariza.ArizaFoto = fotograflar.Select(x => x.Yol).ToList();
                arizaRepo.Update(ariza);
                TempData["Message"] = "Kaydınız alınlıştır";
                return(RedirectToAction("ArizaBildirimi", "Musteri"));
            }
            catch (Exception ex)
            {
                TempData["Model"] = new ErrorViewModel()
                {
                    Text           = $"Bir hata oluştu {ex.Message}",
                    ActionName     = "ArizaBildirimi",
                    ControllerName = "Musteri",
                    ErrorCode      = 500
                };
                return(RedirectToAction("Error", "Home"));
            }
        }
Ejemplo n.º 10
0
        public ActionResult EditProduct(ProductViewModel model, HttpPostedFileBase file)
        {
            // Get product id
            int id = model.Id;

            // Populate categories select list and gallery images
            using (HAPINUTSHOPEntities db = new HAPINUTSHOPEntities())
            {
                model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
            }
            model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Products/" + id + "/Gallery"))
                                  .Select(fn => Path.GetFileName(fn));

            // Check model state
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // Make sure product name is unique
            using (HAPINUTSHOPEntities db = new HAPINUTSHOPEntities())
            {
                if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name))
                {
                    ModelState.AddModelError("", "Tên sản phẩm đã tồn tại!");
                    return(View(model));
                }
            }

            // Update product
            using (HAPINUTSHOPEntities db = new HAPINUTSHOPEntities())
            {
                Product dto = db.Products.Find(id);

                dto.Name       = model.Name;
                dto.Decription = model.Decription;
                dto.Price      = model.Price;
                dto.CategoryId = model.CategoryId;
                dto.ImageName  = model.Image;

                Category catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                dto.CategoryName = catDTO.Name;

                db.SaveChanges();
            }

            // Set TempData message
            TempData["SM"] = "Thay đổi thành công!";

            #region Image Upload

            // Check for file upload
            if (file != null && file.ContentLength > 0)
            {
                // Get extension
                string ext = file.ContentType.ToLower();

                // Verify extension
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (HAPINUTSHOPEntities db = new HAPINUTSHOPEntities())
                    {
                        ModelState.AddModelError("", "Không thể upload hình ảnh, vui lòng kiểm tra lại định dạng!");
                        return(View(model));
                    }
                }

                // Set uplpad directory paths
                var originalDirectory = new DirectoryInfo(string.Format("{0}Images", Server.MapPath(@"\")));

                //var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
                var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery");

                // Delete files from directories

                //DirectoryInfo di1 = new DirectoryInfo(pathString1);
                DirectoryInfo di2 = new DirectoryInfo(pathString2);

                //foreach (FileInfo file2 in di1.GetFiles())
                //    file2.Delete();

                foreach (FileInfo file3 in di2.GetFiles())
                {
                    file3.Delete();
                }

                // Save image name

                string imageName = file.FileName;

                using (HAPINUTSHOPEntities db = new HAPINUTSHOPEntities())
                {
                    Product dto = db.Products.Find(id);
                    dto.ImageName = imageName;

                    db.SaveChanges();
                }

                // Save original and thumb images

                //var path = string.Format("{0}\\{1}", pathString1, imageName);
                var path2 = string.Format("{0}\\{1}", pathString2, imageName);

                //file.SaveAs(path);

                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }

            #endregion

            // Redirect
            return(RedirectToAction("Products"));
        }
Ejemplo n.º 11
0
        public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file)
        {
            //Проверка модели на валидность
            if (!ModelState.IsValid)
            {
                using (Db db = new Db())
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    return(View(model));
                }
            }

            //Проверка имени продуктa на уникальность
            using (Db db = new Db())
            {
                if (db.Products.Any(x => x.Name == model.Name))
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    ModelState.AddModelError("", "Такое название рекламы уже существует.");
                    return(View(model));
                }
            }

            //Объявление переменной ProductId
            int id;

            //Инициализация и сохранение модели на основе ProductDTO
            using (Db db = new Db())
            {
                ProductDTO product = new ProductDTO();

                product.Name        = model.Name;
                product.Slug        = model.Name.Replace(" ", "-").ToLower();;
                product.Description = model.Description;
                product.Price       = model.Price;
                product.CategoryId  = model.CategoryId;

                CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                product.CategoryName = catDTO.Name;

                db.Products.Add(product);
                db.SaveChanges();

                id = product.Id;
            }

            //Вывод сообщения в TempData
            TempData["M"] = "Вы добавили рекламу";

            #region Upload Image

            //Создание ссылок на директории
            var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads"));

            var pathString1 = Path.Combine(originalDirectory.ToString(), "Products");
            var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
            var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Small");
            var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery");
            var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Small");

            //Проверка на существование директорий, создание если нужно
            if (!Directory.Exists(pathString1))
            {
                Directory.CreateDirectory(pathString1);
            }

            if (!Directory.Exists(pathString2))
            {
                Directory.CreateDirectory(pathString2);
            }

            if (!Directory.Exists(pathString3))
            {
                Directory.CreateDirectory(pathString3);
            }

            if (!Directory.Exists(pathString4))
            {
                Directory.CreateDirectory(pathString4);
            }

            if (!Directory.Exists(pathString5))
            {
                Directory.CreateDirectory(pathString5);
            }

            //Проверка на загрузку файла
            if (file != null && file.ContentLength > 0)
            {
                //Получение расширения файла
                string ext = file.ContentType.ToLower();

                //Проверка расширения файла
                if (ext != "image/jpg" &&
                    ext != "image/png" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png")
                {
                    using (Db db = new Db())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "Картинка не загружена. Недопустимое расширение.");
                        return(View(model));
                    }
                }

                //Объявление переменной с именем изображения
                string imageName = file.FileName;

                //Сохранение имени в модель DTO
                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;

                    db.SaveChanges();
                }

                //Назначение пути к оригинальному и уменьшенному изображению
                var path  = string.Format($"{pathString2}\\{imageName}");  //к оригинальному изображению
                var path2 = string.Format($"{pathString3}\\{imageName}");  //к уменьшенному

                //Сохранение оригинального изображения
                file.SaveAs(path);

                //Создание и сохранение уменьшенной картинки
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200).Crop(1, 1);
                img.Save(path2);
            }

            #endregion

            //Переадресовка пользователя
            return(RedirectToAction("AddProduct"));
        }
        public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file)
        {
            // pobranie id produktu
            int id = model.Id;

            // pobranie kategorii dla listy rozwijanej
            using (Database db = new Database())
            {
                model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
            }

            // ustawiamy zdjecia
            model.GalleryImages = Directory
                                  .EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs"))
                                  .Select(fn => Path.GetFileName(fn));

            // sprawdzamy model state (czy nasz formularz jest poprawnie wypełniony)
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // sprawdzenie unikalności nazwy produktu
            using (Database db = new Database())
            {
                if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name))
                {
                    ModelState.AddModelError("", "Ta nazwa produktu jest zajęta");
                    return(View(model));
                }
            }

            // Edycja produktu i zapis na bazie
            using (Database db = new Database())
            {
                ProductDTO dto = db.Products.Find(id);
                dto.Name        = model.Name;
                dto.Slug        = model.Name.Replace(" ", "-").ToLower();
                dto.Description = model.Description;
                dto.Price       = model.Price;
                dto.CategoryId  = model.CategoryId;
                dto.ImageName   = model.ImageName;

                //sprawdzenie nazwy po idku
                CategoryDTO catDto = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                dto.CategoryName = catDto.Name;

                db.SaveChanges();
            }

            // ustawienie TempData
            TempData["SM"] = "Edytowałeś produkt";

            #region Image Upload

            // sprawdzamy czy jest plik
            if (file != null && file.ContentLength > 0)
            {
                // sprawdzamy rozszerzenie pliku czy to jest obrazek
                string ext = file.ContentType.ToLower();

                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Database db = new Database())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "Obraz nie został przesłany - nieprawidłowe rozszerzenie obrazu.");
                        return(View(model));
                    }
                }

                //utworzenie potrzebnej struktury katalogów
                var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

                var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
                var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");

                // usuwamy stare pliki z katalogów
                DirectoryInfo di1 = new DirectoryInfo(pathString1);
                DirectoryInfo di2 = new DirectoryInfo(pathString2);

                foreach (var file2 in di1.GetFiles())
                {
                    file2.Delete();
                }

                foreach (var file3 in di2.GetFiles())
                {
                    file3.Delete();
                }

                // zapisujemy nazwę obrazkę na bazie
                string imageName = file.FileName;

                using (Database db = new Database())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;
                    db.SaveChanges();
                }

                // Zapis nowych pliku
                var path  = string.Format("{0}\\{1}", pathString1, imageName);
                var path2 = string.Format("{0}\\{1}", pathString2, imageName);

                //zapisujemy plik obrazka
                file.SaveAs(path);

                //zapisujemy plik miniaturki i zmniejszamy wielkość obrazka głównego
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }

            #endregion



            return(RedirectToAction("EditProduct"));
        }
        public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file)
        {
            //sprawdzamy model state
            if (!ModelState.IsValid)
            {
                //kontekst
                using (Database db = new Database())
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    return(View(model));
                }
            }


            // sprawdzenie czy nazwa produktu jest unikalna
            //kontekst
            using (Database db = new Database())
            {
                if (db.Products.Any(x => x.Name == model.Name))
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    ModelState.AddModelError("", "Ta nazwa produktu jest zajęta");
                    return(View(model));
                }
            }

            //deklaracja prductId
            int id;

            // dodawanie produktu i zapis na bazie
            using (Database db = new Database())
            {
                ProductDTO product = new ProductDTO();
                product.Name        = model.Name;
                product.Slug        = model.Name.Replace(" ", "-").ToLower();
                product.Description = model.Description;
                product.Price       = model.Price;
                product.CategoryId  = model.CategoryId;

                CategoryDTO catDto = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                product.CategoryName = catDto.Name;

                db.Products.Add(product);
                db.SaveChanges();

                // pobranie id dodanego produktu
                id = product.Id;
            }

            //ustawiamy komunikat
            TempData["SM"] = "Dodałeś produkt";

            #region Upload Image

            //utworzenie potrzebnej struktury katalogów
            var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

            var pathString1 = Path.Combine(originalDirectory.ToString(), "Products");
            var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
            var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");
            var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery");
            var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs");

            if (!Directory.Exists(pathString1))
            {
                Directory.CreateDirectory(pathString1);
            }

            if (!Directory.Exists(pathString2))
            {
                Directory.CreateDirectory(pathString2);
            }

            if (!Directory.Exists(pathString3))
            {
                Directory.CreateDirectory(pathString3);
            }

            if (!Directory.Exists(pathString4))
            {
                Directory.CreateDirectory(pathString4);
            }

            if (!Directory.Exists(pathString5))
            {
                Directory.CreateDirectory(pathString5);
            }

            if (file != null && file.ContentLength > 0)
            {
                // sprawdzenie rozszerzenia pliku czy mamy do czynienia z obrazkiem
                string ext = file.ContentType.ToLower();
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Database db = new Database())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "Obraz nie został przesłany - nieprawidłowe rozszerzenie obrazu.");
                        return(View(model));
                    }
                }

                // inicjalizacja nazwy obrazka
                string imgName = file.FileName;

                // zapis nazwy obrazka do bazy
                using (Database db = new Database())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imgName;
                    db.SaveChanges();
                }

                var path  = string.Format("{0}\\{1}", pathString2, imgName);
                var path2 = string.Format("{0}\\{1}", pathString3, imgName);

                //zapisujemy oryginalny obrazek
                file.SaveAs(path);

                //zapisujemy miniaturkę
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }



            #endregion

            return(RedirectToAction("AddProduct"));
        }
        public async Task <ActionResult> ArizaEkle(ArizaViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Errör");
                return(View());
            }
            Ariza yeniAriza = new Ariza()
            {
                Baslik      = model.Baslik,
                Aciklama    = model.Aciklama,
                Adres       = model.Adres,
                Boylam      = model.Boylam,
                Enlem       = model.Enlem,
                ModelID     = model.ModelID,
                MarkaID     = model.MarkaID,
                KullaniciID = HttpContext.User.Identity.GetUserId()
            };

            new ArizaRepo().Insert(yeniAriza);
            if (model.Dosyalar.Count > 0)
            {
                model.Dosyalar.ForEach(file =>
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        string fileName = Path.GetFileNameWithoutExtension(file.FileName);
                        string extName  = Path.GetExtension(file.FileName);
                        fileName        = fileName.Replace(" ", "");
                        fileName       += Guid.NewGuid().ToString().Replace("-", "");
                        fileName        = SiteSettings.UrlFormatConverter(fileName);
                        var klasoryolu  = Server.MapPath("~/Upload/" + yeniAriza.ID);
                        var dosyayolu   = Server.MapPath("~/Upload/" + yeniAriza.ID + "/") + fileName + extName;
                        if (!Directory.Exists(klasoryolu))
                        {
                            Directory.CreateDirectory(klasoryolu);
                        }
                        file.SaveAs(dosyayolu);
                        WebImage img = new WebImage(dosyayolu);
                        img.Resize(870, 480, false);
                        img.AddTextWatermark("Pc-Service", "RoyalBlue", opacity: 75, fontSize: 25, fontFamily: "Verdana", horizontalAlign: "Left");
                        img.Save(dosyayolu);
                        new FotografRepo().Insert(new Fotograf()
                        {
                            ArizaID = yeniAriza.ID,
                            Yol     = @"Upload/" + yeniAriza.ID + "/" + fileName + extName
                        });
                    }
                });
            }
            string SiteUrl = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host +
                             (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port);
            var roleManager = MembershipTools.NewRoleManager();
            var users       = roleManager.FindByName("Admin").Users;

            var           userManager = MembershipTools.NewUserManager();
            List <string> mailler     = new List <string>();

            foreach (var item in users)
            {
                mailler.Add(userManager.FindById(item.UserId).Email);
            }

            foreach (var mail in mailler)
            {
                await SiteSettings.SendMail(new MailModel
                {
                    Subject = "Yeni Arıza Bildirimi",
                    Message = $"Sayın Operatör,<br/>Sitenize bir arıza eklendi, Lütfen gereken işlemleri gerçekleştirin.<br/><a href='{SiteUrl}/Admin/ArizaDetay/{yeniAriza.ID}'>Haydi Onayla</a><p>İyi Çalışmalar<br/>Sitenin Nöbetçisi</p>",
                    To      = mail
                });
            }
            return(RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 15
0
        public void SaveUsesInitialFormatWhenNoFormatIsSpecified()
        {
            // Arrange
            string savePath = @"x:\some-dir\image.png";
            MemoryStream stream = null;
            Action<string, byte[]> saveAction = (path, content) => { stream = new MemoryStream(content); };
            var image = new WebImage(_PngImageBytes);

            // Act 
            image.FlipVertical().FlipHorizontal();

            // Assert
            image.Save(GetContext(), saveAction, savePath, imageFormat: null, forceWellKnownExtension: true);

            using (Image savedImage = Image.FromStream(stream))
            {
                Assert.Equal(savedImage.RawFormat, ImageFormat.Png);
            }
        }
        public ActionResult EditProduct(Product model, HttpPostedFileBase file)
        {
            // Get product id
            int id = model.Id;

            // Populate categories select list and gallery images
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                model.Catagories = new SelectList(db.Catagories.ToList(), "Id", "Name");
            }
            model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs"))
                                  .Select(fn => Path.GetFileName(fn));

            //Check model state
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //Make sure product name is unique
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name))
                {
                    ModelState.AddModelError("", "That product name is taken!");
                    return(View(model));
                }
            }
            //Update product
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                Product product = db.Products.Find(id);
                product.Name        = model.Name;
                product.Description = model.Description;
                product.Price       = model.Price;
                product.CatagoryId  = model.CatagoryId;
                product.ImageName   = model.ImageName;

                Catagory catDTO = db.Catagories.FirstOrDefault(x => x.Id == model.CatagoryId);
                product.CatagoryName = catDTO.Name;
                db.SaveChanges();
            }

            //Set TempData
            TempData["SM"] = "You have edited the Product!";

            #region Image Upload
            //Check for file upload
            if (file != null && file.ContentLength > 0)
            {
                //Get extension
                string ext = file.ContentType.ToLower();
                // verify extension
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (ApplicationDbContext db = new ApplicationDbContext())
                    {
                        ModelState.AddModelError("", "The image was not uploaded - wrong image extension.");
                        return(View(model));
                    }
                }

                //Set upload dircetories path
                var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

                var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
                var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");

                //Delete files from directories
                DirectoryInfo di1 = new DirectoryInfo(pathString1);
                DirectoryInfo di2 = new DirectoryInfo(pathString2);

                foreach (FileInfo file2 in di1.GetFiles())
                {
                    file2.Delete();
                }
                foreach (FileInfo file3 in di2.GetFiles())
                {
                    file3.Delete();
                }

                //Save image name
                string imageName = file.FileName;
                using (ApplicationDbContext db = new ApplicationDbContext())
                {
                    Product product = db.Products.Find(id);
                    product.ImageName = imageName;
                    db.SaveChanges();
                }
                //Save original and thumb images
                var path  = string.Format("{0}\\{1}", pathString1, imageName);
                var path2 = string.Format("{0}\\{1}", pathString2, imageName);

                file.SaveAs(path);
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }
            #endregion

            //Redirect
            return(RedirectToAction("EditProduct"));
        }
Ejemplo n.º 17
0
        public void ResizePreservesFormat()
        {
            // Arrange
            WebImage image = new WebImage(_PngImageBytes);
            MemoryStream output = null;
            Action<string, byte[]> saveAction = (_, content) => { output = new MemoryStream(content); };

            // Act
            image.Resize(200, 100, preserveAspectRatio: true, preventEnlarge: true);

            // Assert
            Assert.Equal(image.ImageFormat, "png");
            image.Save(GetContext(), saveAction, @"x:\1.png", null, false);

            using (Image modified = Image.FromStream(output))
            {
                Assert.Equal(ImageFormat.Png, modified.RawFormat);
            }
        }
        public async Task <ActionResult> CreateAdminUser(UserVM userVM, HttpPostedFileBase file)
        {
            if (!ModelState.IsValid)
            {
                return(View(userVM));
            }

            int idForAvatar = 0;

            using (ChekitDB chekitDB = new ChekitDB())
            {
                if (await chekitDB.Users.AnyAsync(x => x.Login == userVM.Login))
                {
                    ModelState.AddModelError("loginmatch", $"Логин {userVM.Login} занят");

                    return(View(userVM));
                }
                else if (await chekitDB.Users.AnyAsync(x => x.Email == userVM.Email))
                {
                    ModelState.AddModelError("emailmatch", $"Email {userVM.Email} занят");

                    return(View(userVM));
                }

                UsersDTO usersDTO = new UsersDTO();

                usersDTO.Login      = userVM.Login;
                usersDTO.Email      = userVM.Email;
                usersDTO.Password   = userVM.Password;
                usersDTO.BanStatus  = false;
                usersDTO.LinksCount = 0;
                usersDTO.Role       = "Админ";

                chekitDB.Users.Add(usersDTO);
                await chekitDB.SaveChangesAsync();

                int id     = usersDTO.UserId;
                int roleId = 1;

                UserRoleDTO userRole = new UserRoleDTO()
                {
                    UserId = id,
                    RoleId = roleId
                };

                chekitDB.UserRoles.Add(userRole);
                await chekitDB.SaveChangesAsync();

                idForAvatar = usersDTO.UserId;
            }

            TempData["OK"] = "Админ создан";

            #region UploadAvatar

            var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Avatars\\Uploads"));

            var pathString1 = Path.Combine(originalDirectory.ToString(), "UserAvatars");
            var pathString2 = Path.Combine(originalDirectory.ToString(), "UserAvatars\\" + idForAvatar.ToString());
            var pathString3 = Path.Combine(originalDirectory.ToString(), "UserAvatars\\" + idForAvatar.ToString() + "\\Thumbs");
            var pathString4 = Path.Combine(originalDirectory.ToString(), "UserAvatars\\" + idForAvatar.ToString() + "\\Gallery");
            var pathString5 = Path.Combine(originalDirectory.ToString(), "UserAvatars\\" + idForAvatar.ToString() + "\\Gallery\\Thumbs");

            if (!Directory.Exists(pathString1))
            {
                Directory.CreateDirectory(pathString1);
            }

            if (!Directory.Exists(pathString2))
            {
                Directory.CreateDirectory(pathString2);
            }

            if (!Directory.Exists(pathString3))
            {
                Directory.CreateDirectory(pathString3);
            }

            if (!Directory.Exists(pathString4))
            {
                Directory.CreateDirectory(pathString4);
            }

            if (!Directory.Exists(pathString5))
            {
                Directory.CreateDirectory(pathString5);
            }

            string[] extensions = { "image/jpg", "image/jpeg", "image/gif", "image/png" };

            if (file != null && file.ContentLength > 0)
            {
                string extension = file.ContentType.ToLower();
                int    counter   = 0;

                foreach (var item in extensions)
                {
                    if (extension != item)
                    {
                        counter++;

                        if (counter == extensions.Length)
                        {
                            ModelState.AddModelError("errorFormat", "Неправильный формат файла");

                            return(View(userVM));
                        }
                    }
                }

                string avatarName = file.FileName;

                using (ChekitDB chekitDB = new ChekitDB())
                {
                    UsersDTO usersDTO = await chekitDB.Users.FindAsync(idForAvatar);

                    usersDTO.AvatarName = avatarName;

                    await chekitDB.SaveChangesAsync();
                }

                var pathOriginalAvatar = string.Format($"{pathString2}\\{avatarName}");
                var pathLittleAvatar   = string.Format($"{pathString3}\\{avatarName}");

                file.SaveAs(pathOriginalAvatar);

                WebImage littleAvatar = new WebImage(file.InputStream);
                littleAvatar.Resize(150, 150);
                littleAvatar.Save(pathLittleAvatar);
            }

            #endregion

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 19
0
        public void SaveOverwritesExistingFile()
        {
            Action<string, byte[]> saveAction = (path, content) => { };

            WebImage image = new WebImage(_BmpImageBytes);
            string newFileName = @"x:\newImage.bmp";

            image.Save(GetContext(), saveAction, newFileName, imageFormat: null, forceWellKnownExtension: true);

            image.RotateLeft();
            // just verify this does not throw
            image.Save(GetContext(), saveAction, newFileName, imageFormat: null, forceWellKnownExtension: true);
        }
        public async Task <ActionResult> EditUser(UserProfileVM userVM, HttpPostedFileBase file)
        {
            int userId = userVM.UserId;

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

            using (ChekitDB chekitDB = new ChekitDB())
            {
                if (await chekitDB.Users.Where(x => x.UserId != userVM.UserId).AnyAsync(x => x.Login == userVM.Login))
                {
                    ModelState.AddModelError("loginmatch", $"Логин {userVM.Login} занят");

                    return(View(userVM));
                }
                else if (await chekitDB.Users.Where(x => x.UserId != userVM.UserId).AnyAsync(x => x.Email == userVM.Email))
                {
                    ModelState.AddModelError("emailmatch", $"Email {userVM.Email} занят");

                    return(View(userVM));
                }
            }

            using (ChekitDB chekitDB = new ChekitDB())
            {
                UsersDTO usersDTO = await chekitDB.Users.FindAsync(userId);

                usersDTO.Login      = userVM.Login;
                usersDTO.Email      = userVM.Email;
                usersDTO.Password   = usersDTO.Password;
                usersDTO.AvatarName = userVM.AvatarName;

                await chekitDB.SaveChangesAsync();
            }

            TempData["OK"] = "Профиль отредактирован";

            #region Image Upload

            if (file != null && file.ContentLength > 0)
            {
                string extension = file.ContentType.ToLower();

                string[] extensions = { "image/jpg", "image/jpeg", "image/gif", "image/png" };
                int      counter    = 0;

                //Проверяем расширение файла
                foreach (var item in extensions)
                {
                    if (extension != item)
                    {
                        counter++;

                        if (counter == extensions.Length)
                        {
                            using (ChekitDB chekitDB = new ChekitDB())
                            {
                                ModelState.AddModelError("", "Изображение не было загружено - неправильный формат изображения");

                                return(View(userVM));
                            }
                        }
                    }
                }

                var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Avatars\\Uploads"));

                var pathString1 = Path.Combine(originalDirectory.ToString(), "UserAvatars\\" + userId.ToString());
                var pathString2 = Path.Combine(originalDirectory.ToString(), "UserAvatars\\" + userId.ToString() + "\\Thumbs");

                DirectoryInfo directoryInfo1 = new DirectoryInfo(pathString1);
                DirectoryInfo directoryInfo2 = new DirectoryInfo(pathString2);

                foreach (var item in directoryInfo1.GetFiles())
                {
                    item.Delete();
                }

                foreach (var item in directoryInfo2.GetFiles())
                {
                    item.Delete();
                }

                string avatarName = file.FileName;

                using (ChekitDB chekitDB = new ChekitDB())
                {
                    UsersDTO usersDTO = await chekitDB.Users.FindAsync(userId);

                    usersDTO.AvatarName = avatarName;

                    await chekitDB.SaveChangesAsync();
                }

                var pathOriginalAvatar = string.Format($"{pathString1}\\{avatarName}");
                var pathLittleAvatar   = string.Format($"{pathString2}\\{avatarName}");

                file.SaveAs(pathOriginalAvatar);

                WebImage littleAvatar = new WebImage(file.InputStream);
                littleAvatar.Resize(150, 150);
                littleAvatar.Save(pathLittleAvatar);
            }

            #endregion

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 21
0
        public ActionResult Edit(string id, UserVM model, string txtAdres, HttpPostedFileBase txtFoto)
        {
            using (eTicaretEntities db = new eTicaretEntities())
            {
                Resimler r           = new Resimler();
                string   newFoto     = "";
                var      loginedUser = Membership.GetUser(id);
                var      musteris    = db.Musteris.Where(x => x.ID == (Guid)loginedUser.ProviderUserKey).SingleOrDefault();
                if (musteris == null)
                {
                    if (txtFoto != null)
                    {
                        WebImage img  = new WebImage(txtFoto.InputStream);
                        FileInfo info = new FileInfo(txtFoto.FileName);
                        newFoto = Guid.NewGuid().ToString() + info.Extension;
                        img.Resize(100, 150);
                        img.Save("~/Upload/KullaniciPP/" + newFoto);
                        r.KucukYol = "/Upload/KullaniciPP/" + newFoto;
                        db.Resimlers.Add(r);
                    }
                    var resim = db.Resimlers.Where(x => x.KucukYol == "/Upload/KullaniciPP/" + newFoto).SingleOrDefault();
                    model.Musteriler.KullaniciAdi = id;
                    model.Musteriler.EMail        = loginedUser.Email;
                    model.Musteriler.ID           = (Guid)loginedUser.ProviderUserKey;
                    model.Musteriler.ResimID      = r.ID;
                    db.Musteris.Add(model.Musteriler);
                    MusteriAdresler adres = new MusteriAdresler()
                    {
                        Ad        = model.Musteriler.Ad,
                        Adres     = txtAdres,
                        MusteriID = model.Musteriler.ID
                    };
                    db.MusteriAdreslers.Add(adres);
                }
                else
                {
                    var musteri = db.Musteris.Where(x => x.ID == (Guid)loginedUser.ProviderUserKey).SingleOrDefault();
                    var rsm     = db.Resimlers.Where(x => x.ID == musteri.ResimID).SingleOrDefault();

                    if (txtFoto != null)
                    {
                        if (rsm != null)
                        {
                            if (System.IO.File.Exists(Server.MapPath(rsm.KucukYol)))
                            {
                                System.IO.File.Delete(Server.MapPath(rsm.KucukYol));
                            }
                        }
                        WebImage img  = new WebImage(txtFoto.InputStream);
                        FileInfo info = new FileInfo(txtFoto.FileName);
                        newFoto = Guid.NewGuid().ToString() + info.Extension;
                        img.Resize(100, 150);
                        img.Save("~/Upload/KullaniciPP/" + newFoto);
                        r.KucukYol = "/Upload/KullaniciPP/" + newFoto;
                        db.Resimlers.Add(r);
                        musteri.ResimID = r.ID;
                    }
                    musteri.Ad      = model.Musteriler.Ad;
                    musteri.Soyad   = model.Musteriler.Soyad;
                    musteri.Telefon = model.Musteriler.Telefon;
                    MusteriAdresler adres = new MusteriAdresler();
                    adres.Adres = txtAdres;
                }

                db.SaveChanges();
                return(RedirectToAction("Profil", new { id = id }));
            }
        }
Ejemplo n.º 22
0
        public ActionResult AddProduct(ProductVM obj, HttpPostedFileBase file)
        {
            //Check ModelState is Valid
            if (!ModelState.IsValid)
            {
                using (Db _context = new Db())
                {
                    obj.Catagories = new SelectList(_context.Catagories.ToList(), "Id", "Name");
                    return(View(obj));
                }
            }

            //MakeSure the Product Name is unique

            using (Db _context = new Db())
            {
                if (_context.Products.Any(a => a.Name == obj.Name))
                {
                    obj.Catagories = new SelectList(_context.Catagories.ToList(), "Id", "Name");
                    ModelState.AddModelError("", "The Product Name is Taken..!");
                    return(View(obj));
                }
            }

            //Declare Product ID
            int Id;

            //Init And save ProductDTO
            using (Db _context = new Db())
            {
                ProductDTO objPro = new ProductDTO();
                objPro.Name        = obj.Name;
                objPro.Description = obj.Description;
                objPro.Slug        = obj.Name.Replace(" ", "-").ToLower();
                objPro.Price       = obj.Price;
                objPro.CatagoryId  = obj.CatagoryId;

                CatagoryDTO objCat = _context.Catagories.FirstOrDefault(x => x.Id == obj.CatagoryId);
                objPro.catagoryName = objCat.Name;

                _context.Products.Add(objPro);
                _context.SaveChanges();

                //Get the ID

                Id = objPro.Id;
            }


            //Set tempData Message
            TempData["SM"] = "You Have Added the product Succesfuly";


            #region Upload_Image

            //Create The Necessary Directories
            var OriginalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

            string PathString1 = Path.Combine(OriginalDirectory.ToString(), "Products");
            string PathString2 = Path.Combine(OriginalDirectory.ToString(), "Products\\" + Id.ToString());
            string PathString3 = Path.Combine(OriginalDirectory.ToString(), "Products\\" + Id.ToString() + "\\Thumbs");
            string PathString4 = Path.Combine(OriginalDirectory.ToString(), "Products\\" + Id.ToString() + "\\Gallary");
            string PathString5 = Path.Combine(OriginalDirectory.ToString(), "Products\\" + Id.ToString() + "\\Gallary\\Thumbs");

            if (!Directory.Exists(PathString1))
            {
                Directory.CreateDirectory(PathString1);
            }
            if (!Directory.Exists(PathString2))
            {
                Directory.CreateDirectory(PathString2);
            }
            if (!Directory.Exists(PathString3))
            {
                Directory.CreateDirectory(PathString3);
            }
            if (!Directory.Exists(PathString4))
            {
                Directory.CreateDirectory(PathString4);
            }
            if (!Directory.Exists(PathString5))
            {
                Directory.CreateDirectory(PathString5);
            }

            //Check If the File was Upload
            if (file != null && file.ContentLength > 0)
            {
                //Get the File Extension
                string ex = file.ContentType.ToLower();

                //Verify the file Extension
                if (ex != "image/jpg" &&
                    ex != "image/jpeg" &&
                    ex != "image/pjepg" &&
                    ex != "image/gif" &&
                    ex != "image/x-png" &&
                    ex != "image/png")
                {
                    using (Db _context = new Db())
                    {
                        obj.Catagories = new SelectList(_context.Catagories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "The Image was not Uploaded- Wrong Image Extension..!");
                        return(View(obj));
                    }
                }

                //Init the Image Name
                string ImagName = file.FileName;

                //Save ImageName to DTO
                using (Db _context = new Db())
                {
                    ProductDTO objP = _context.Products.Find(Id);
                    objP.ImgName = ImagName;
                    _context.SaveChanges();
                }

                //Set Original And Thumb  Images Paths


                var path1 = string.Format("{0}\\{1}", PathString2, ImagName);
                var path2 = string.Format("{0}\\{1}", PathString3, ImagName);

                //Save  Original
                file.SaveAs(path1);

                //Create and Save Thumb
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }
            #endregion

            return(RedirectToAction("AddProduct"));
        }
Ejemplo n.º 23
0
 private void GuardarImagenEnServidor(WebImage image, string path, string fileName)
 {
     image.Save(Path.Combine("~" + path + fileName));
     image = null;
 }
Ejemplo n.º 24
0
        public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file)
        {
            //get product Id

            int id = model.Id;

            //populate the catagory select list amd Image Gallery
            using (Db _context = new Db())
            {
                model.Catagories = new SelectList(_context.Catagories.ToList(), "Id", "Name");
            }
            model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallary/Thumbs"))
                                  .Select(fn => Path.GetFileName(fn));

            //Check the Model State
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //Make sure the product name is unique..
            using (Db _context = new Db())
            {
                if (_context.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name))
                {
                    ModelState.AddModelError("", "The name of the Products is exist...!");
                    return(View(model));
                }
            }

            //Update the Product...
            using (Db _context = new Db())
            {
                ProductDTO obj = _context.Products.Find(id);
                obj.Name  = model.Name;
                obj.Slug  = model.Name.Replace(" ", "-").ToLower();
                obj.Price = model.Price;
                obj.Description
                               = model.Description;
                obj.CatagoryId = model.CatagoryId;
                if (model.ImgName != null)
                {
                    obj.ImgName = model.ImgName;
                }


                CatagoryDTO objcat = _context.Catagories.FirstOrDefault(x => x.Id == model.CatagoryId);
                obj.catagoryName = objcat.Name;

                _context.SaveChanges();
            }

            //Set tempdate message
            TempData["SM"] = "You have Edit the product successfuly..";

            #region Image Upload
            //Check the File Upload
            if (file != null && file.ContentLength > 0)
            {
                //Get the Extension
                string exe = file.ContentType.ToLower();


                //verify the extension

                if (exe != "image/jpg" &&
                    exe != "image/jpeg" &&
                    exe != "image/pjepg" &&
                    exe != "image/gif" &&
                    exe != "image/x-png" &&
                    exe != "image/png")
                {
                    using (Db _context = new Db())
                    {
                        ModelState.AddModelError("", "The Image was not Uploaded- Wrong Image Extension..!");
                        return(View(model));
                    }
                }


                //Set Upload Directory Path
                var OriginalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

                string PathString1 = Path.Combine(OriginalDirectory.ToString(), "Products\\" + id.ToString());
                string PathString2 = Path.Combine(OriginalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");


                //Delete Files From Directorr

                DirectoryInfo dI1 = new DirectoryInfo(PathString1);
                DirectoryInfo dI2 = new DirectoryInfo(PathString2);

                foreach (FileInfo item in dI1.GetFiles())
                {
                    item.Delete();
                }

                foreach (FileInfo item1 in dI2.GetFiles())
                {
                    item1.Delete();
                }


                //Save Image Name

                string ImName = file.FileName;

                using (Db _context = new Db())
                {
                    ProductDTO objP = _context.Products.Find(id);
                    objP.ImgName = ImName;
                    _context.SaveChanges();
                }

                //Set the Original and Thumbs Imagess
                var path1 = string.Format("{0}\\{1}", PathString1, ImName);
                var path2 = string.Format("{0}\\{1}", PathString2, ImName);

                //Save  Original
                file.SaveAs(path1);

                //Create and Save Thumb
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }



            #endregion

            return(RedirectToAction("EditProduct"));
        }
Ejemplo n.º 25
0
        public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file)//its to receive a viewmodel ProductVM and  a File
        {
            //Get product id
            int id = model.Id;

            //Populate categories select list and gallery images
            model.Categories    = new SelectList(db.Categories.ToList(), "Id", "Name");
            model.GalleryImages = Directory.EnumerateFiles(Server.
                                                           MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thubs"))
                                  .Select(fileName => Path.GetFileName(fileName));
            //Check model state
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //Make sure product name is unique
            if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name))
            {
                ModelState.AddModelError("", "That product name is taken!");
                return(View(model));
            }
            //Update Product
            Product dto = db.Products.Find(id);

            dto.Name        = model.Name;
            dto.Slug        = model.Name.Replace(" ", "-").ToLower();
            dto.Price       = model.Price;
            dto.Description = model.Description;
            dto.CategoryId  = model.CategoryId;
            dto.ImageName   = model.ImageName;

            Category catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);//with a foreign key relationship of Categories Name in Products

            dto.CategoryName = catDTO.Name;

            db.SaveChanges();

            //Set TempData message
            TempData["SM"] = "You have edited the product";

            //for image edit & upload
            #region Image upload

            //Check for file upload
            if (file != null && file.ContentLength > 0)
            {
                //Get extension
                string ext = file.ContentType.ToLower();

                //Verify extension
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjeg" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    ModelState.AddModelError("", "The image was not uploaded -wrong image extension");
                    return(View(model));
                }


                //Set upload directory paths
                var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

                var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());             // creates another folder
                var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thubs"); //creates another folder for thubs

                //Delete files from directories
                DirectoryInfo di1 = new DirectoryInfo(pathString2);
                DirectoryInfo di2 = new DirectoryInfo(pathString3);

                foreach (FileInfo file2 in di1.GetFiles())
                {
                    file2.Delete();                                        //delete existing files
                }
                foreach (FileInfo file3 in di2.GetFiles())
                {
                    file3.Delete();
                }


                //Save image name

                string imageName = file.FileName;

                Product dto2 = db.Products.Find(id);
                dto2.ImageName = imageName;
                db.SaveChanges();

                //Save original and thumb images

                var path  = string.Format("{0}\\{1}", pathString2, imageName);
                var path2 = string.Format("{0}\\{1}", pathString3, imageName);


                file.SaveAs(path);

                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }

            #endregion

            //Redirect
            return(RedirectToAction("EditProduct"));
        }
Ejemplo n.º 26
0
        public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file)
        {
            int id = model.Id;

            using (Db db = new Db())
            {
                model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
            }
            model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs")).Select(fn => Path.GetFileName(fn));
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            using (Db db = new Db())
            {
                if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name))
                {
                    ModelState.AddModelError("", "Products name is taken!");
                    return(View(model));
                }
            }
            using (Db db = new Db())
            {
                ProductDTO dto = db.Products.Find(id);
                dto.Name        = model.Name;
                dto.Slug        = model.Name.Replace(" ", "-").ToLower();
                dto.Description = model.Description;
                dto.Price       = model.Price;
                dto.CategoryId  = model.CategoryId;
                dto.ImageName   = model.ImageName;

                CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                dto.CategoryName = catDTO.Name;
                db.SaveChanges();
            }
            #region ImageUpload
            if (file != null && file.ContentLength > 0)
            {
                string ext = file.ContentType.ToLower();

                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Db db = new Db())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "The image was not uploaded or wrong image extension");
                    }
                }
                var originalDirectory = new DirectoryInfo(String.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

                var pathString1 = Path.Combine(originalDirectory.ToString(), "Products");
                var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");

                DirectoryInfo di1 = new DirectoryInfo(pathString1);
                DirectoryInfo di2 = new DirectoryInfo(pathString2);

                foreach (FileInfo file2 in di1.GetFiles())
                {
                    file2.Delete();
                }
                foreach (FileInfo file3 in di2.GetFiles())
                {
                    file3.Delete();
                }
                string imgName = file.FileName;
                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imgName;
                    db.SaveChanges();
                }
                var path  = string.Format("{0}\\{1}", pathString1, imgName);
                var path2 = string.Format("{0}\\{1}", pathString2, imgName);

                file.SaveAs(path);

                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }
            #endregion

            TempData["SM"] = "You have edited the product!";

            return(RedirectToAction("EditProduct"));
        }
Ejemplo n.º 27
0
        public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file)
        {
            //Получить ID
            int id = model.Id;

            //Заполнить список категориями и изображениями
            using (Db db = new Db())
            {
                model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
            }

            model.GalleryImages = Directory
                                  .EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs"))
                                  .Select(fn => Path.GetFileName(fn));
            //Проверка модели на валидность
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //Проверка продукта на уникальность
            using (Db db = new Db())
            {
                if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name))
                {
                    ModelState.AddModelError("", "Имя продукта занято");
                    return(View(model));
                }
            }

            //Обновить продукт в БД
            using (Db db = new Db())
            {
                ProductDTO dto = db.Products.Find(id);
                dto.Name        = model.Name;
                dto.Slug        = model.Name.Replace(" ", "-").ToLower();
                dto.Description = model.Description;
                dto.Color       = model.Color;
                dto.Memory      = model.Memory;
                dto.Price       = model.Price;
                dto.CategoryId  = model.CategoryId;
                dto.ImageName   = model.ImageName;

                CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                dto.CategoryName = catDTO.Name;

                db.SaveChanges();
            }
            //Установить сообщение в ТемпДата
            TempData["SM"] = "Продукт обновлен";

            //загрузка изображения
            #region ImageUpload
            //Проверяем загрузку файла
            if (file != null && file.ContentLength > 0)
            {
                //Получаем расширение файла
                string ext = file.ContentType.ToLower();

                //Проверяем расширение
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Db db = new Db())
                    {
                        ModelState.AddModelError("", "Изображение не было загружено - не верный формат файла!");
                        return(View(model));
                    }
                }
                //Устанавливаем пути загрузки
                var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads"));

                var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
                var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");

                //Удаляем существующие файлы и директории
                DirectoryInfo di1 = new DirectoryInfo(pathString1);
                DirectoryInfo di2 = new DirectoryInfo(pathString2);
                foreach (var file2 in di1.GetFiles())
                {
                    file2.Delete();
                }

                foreach (var file3 in di2.GetFiles())
                {
                    file3.Delete();
                }
                //Сохраняем изображение
                string imageName = file.FileName;

                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;

                    db.SaveChanges();
                }
                //Сохраняем оригинал и превью версии
                var path  = string.Format($"{pathString1}\\{imageName}");
                var path2 = string.Format($"{pathString2}\\{imageName}");

                //Сохраняем оригинальное изображение
                file.SaveAs(path);

                //Создаем и сохраняем уменьшиную копию
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200).Crop(1, 1);
                img.Save(path2);
            }
            #endregion

            //Переадресовать пользователя на представление
            return(RedirectToAction("EditProduct"));
        }
Ejemplo n.º 28
0
        public virtual async Task <ActionResult> Add(RegisterViewModel userViewModel, HttpPostedFileBase userImage)
        {
            if (userViewModel.Id.HasValue)
            {
                ModelState.Remove("Password");
                ModelState.Remove("ConfirmPassword");
            }

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

            if (!userViewModel.Id.HasValue)
            {
                var user = new ApplicationUser
                {
                    UserName       = userViewModel.UserName,
                    Email          = userViewModel.Email,
                    EmailConfirmed = true
                };

                var adminresult = await _userManager.CreateAsync(user, userViewModel.Password);

                if (adminresult.Succeeded)
                {
                    var result = await _userManager.AddToRolesAsync(user.Id, "Admin");

                    if (!result.Succeeded)
                    {
                        ModelState.AddModelError("", result.Errors.First());
                        return(View());
                    }
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First());

                    return(View());
                }

                TempData["message"] = "کاربر جدید با موفقیت در سیستم ثبت شد";
            }
            else
            {
                var user = await _userManager.FindByIdAsync(userViewModel.Id.Value);

                if (user == null)
                {
                    return(HttpNotFound());
                }

                user.UserName = userViewModel.UserName;
                user.Email    = userViewModel.Email;

                await _unitOfWork.SaveAllChangesAsync();

                TempData["message"] = "کاربر مورد نظر با موفقیت ویرایش شد";
            }

            if (userImage != null)
            {
                var img = new WebImage(userImage.InputStream);
                img.Resize(161, 161, true, false).Crop(1, 1);

                img.Save(Server.MapPath("~/UploadedFiles/Avatars/" + userViewModel.UserName + ".png"));
            }


            return(RedirectToAction(MVC.User.Admin.ActionNames.Index));
        }
        public ActionResult EditClient(ClientVM model, HttpPostedFileBase file)
        {
            //Получаем  ID заявки будем использоовать для работы с изображением
            int id = model.Id;

            //Список изображений
            //Получаем все изображения из галереи
            model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Clients/" + id + "/Thumds"))
                                  .Select(fn => Path.GetFileName(fn));

            //проверяем модель на валидность
            if (!ModelState.IsValid)
            {
                return(View(model));
            }


            #region поиск имени на уникальность
            //using(DBContext db  = new DBContext())
            //{
            //    //ищем В выборке все id кроме текущего. Проверяем на совпадения по фамилии
            //    if (db.clients.Where(x => x.Id != id).Any(x=> x.lastName == model.LastName))
            //    {
            //        //ModelState.AddModelError("","Данный клиент уже подовал заявку")
            // return View(model);
            //        //можно в дальнейшем реализовать историю заявок конкретного клиента
            //    }
            //}
            #endregion


            //обновляем продукт
            using (DBContext db = new DBContext())
            {
                //Загружаем старые(необновленные) данные заявки в БД
                Client dto = db.clients.Find(id);

                dto.firstName   = model.FirstName;
                dto.lastName    = model.LastName;
                dto.middleName  = model.MiddleName;
                dto.birthDate   = model.BirthDate;
                dto.dateRequest = DateTime.Now.ToString();
                dto.email       = model.Email;
                dto.image       = model.Image;

                db.SaveChanges();
            }

            //устанавливаем сообщение в темп дату
            //Сообщение пользователю. с помощью темп дата
            TempData["SM"] = "Заявка успешно отредактирована!";

            //загружаем обработанно изображение

            //ЗАГРУЗКА ИЗАБРАЖЕНИЯ
            #region Загрузка изображения на сервер

            // проверяем загружен ли файл
            if (file != null && file.ContentLength > 0)
            {
                //получить разширение файла
                string ext = file.ContentType.ToLower();

                // проверяем полученное разшерение файла
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/png" &&
                    ext != "image/x-png")
                {
                    using (DBContext db = new DBContext())
                    {
                        //model.
                        ModelState.AddModelError("", "Не коректный формат !! Изображение не было загружено!");
                        //Сообщение пользователю. с помощью темп дата
                        TempData["SM"] = "Заявка успешно оформлена! Но без изображения!!!";
                        return(View(model));
                    }
                }

                //устанавливаем пути загрузки
                // создание ссылок дирикторий(папок для картинки). Корневая папка
                var originalDirectory  = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads"));
                var originalDirectory2 = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Archive_Documents\\DocsClient"));


                ////путь к папке и кажому новому клиенту(по id).
                var pathString1 = Path.Combine(originalDirectory.ToString(), "Clients\\" + id.ToString());
                //Путь к  папка для хранения уменьшеной копии
                var pathString2 = Path.Combine(originalDirectory.ToString(), "Clients\\" + id.ToString() + "\\Thumds");

                // папки хранения документов Ворд
                var pathString3 = Path.Combine(originalDirectory2.ToString(), id.ToString());

                // папки хранения документов PDF
                var pathString4 = Path.Combine(originalDirectory2.ToString(), id.ToString());


                //удаляем существуешие старые файлы  и директории.
                DirectoryInfo dir1 = new DirectoryInfo(pathString1);
                DirectoryInfo dir2 = new DirectoryInfo(pathString2);
                DirectoryInfo dir3 = new DirectoryInfo(pathString3);
                DirectoryInfo dir4 = new DirectoryInfo(pathString4);

                //Удаляем подпапки
                foreach (var file2 in dir1.GetFiles())
                {
                    file2.Delete();
                }

                foreach (var file3 in dir2.GetFiles())
                {
                    file3.Delete();
                }

                foreach (var file4 in dir3.GetFiles())
                {
                    file4.Delete();
                }

                foreach (var file5 in dir4.GetFiles())
                {
                    file5.Delete();
                }

                ////сохраняем изображение
                string imageName = file.FileName;
                int    idDocWord = id;

                //сохраняемм оригинал и превью картинки
                //Назначить пути к оригинальному и уменьшеному изабражению
                var path  = string.Format($"{pathString1}\\{imageName}");
                var path2 = string.Format($"{pathString2}\\{imageName}"); // уменьшенное изображене
                var path3 = string.Format($"{pathString2}\\{idDocWord}"); // уменьшенное изображене

                //сохранить оригинальное изображение
                file.SaveAs(path);

                //создаем  и  сохраняем уменьшенную копиию
                //обьект WebImage позволяет работать с изображениями
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200); //Ширина, высота сохраненного изображения.
                img.Save(path2);      // Куда сохраняем уменьшенное изображение
                img.Save(path3);      // Куда сохраняем уменьшенное изображение для документа

                using (DBContext db = new DBContext())
                {
                    string tempPath = $"{path3}\\{imageName}";
                    Client dto      = db.clients.Find(id);
                    dto.image = imageName;

                    dto.imagePathInDoc = tempPath; // сохраняем путь к файлу
                    db.SaveChanges();              //save DB
                }
            }

            #endregion

            workingWord = new WorkingWord();
            // создание ссылок дирикторий(папок для документов). Корневая папка
            var originalDirectoryWordDoc = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Archive_Documents\\"));

            //Создается папка дл хранения дока
            var pathString6 = Path.Combine(originalDirectoryWordDoc.ToString(), "DocsClient\\" + id.ToString() + "\\Document\\");

            // путь к самому документу
            string TestSaveDoc = $@"{pathString6}Result_Client_{id}.pdf";

            //Создание отредактированых документов.
            CreateDocWordOfPdf(id);

            //Переодрeсовать пользователя
            return(RedirectToAction("EditClient"));
        }
Ejemplo n.º 30
0
        public ActionResult Edit(PromoViewModel viewModel)
        {
            CommonDataService cds = new CommonDataService();

            CommonModel cm = new CommonModel();

            cm = cds.GenerateCommonModel();
            Session["FaceBook"]      = cm.FaceBook;
            Session["Twitter"]       = cm.Twitter;
            Session["Youtube"]       = cm.Youtube;
            Session["Instagram"]     = cm.Instagram;
            Session["PhoneNumber"]   = cm.PhoneNumber;
            Session["Email"]         = cm.Email;
            Session["ShoppingHours"] = cm.ShoppingHours;
            PromoDataService dataService = new PromoDataService();
            string           promoId     = (string)Request.Form["edit_PromoId"];
            string           imageString = (string)Request.Form["edit_ImageString"];

            try
            {
                if (ModelState.IsValid)
                {
                    WebImage photo       = null;
                    var      newFileName = "";
                    var      imagePath   = "";

                    photo = WebImage.GetImageFromRequest();
                    if (photo != null)
                    {
                        newFileName = Guid.NewGuid().ToString() + "_" +
                                      Path.GetFileName(photo.FileName);
                        imagePath = @"Contents\Images\Promo\" + newFileName;

                        photo.Save(@"~\" + imagePath);
                        viewModel.PromoModel.PromoId     = int.Parse(promoId);
                        viewModel.PromoModel.ImageString = imagePath;
                    }
                    else
                    {
                        viewModel.PromoModel.PromoId     = int.Parse(promoId);
                        viewModel.PromoModel.ImageString = imageString;
                    }

                    dataService.UpdatePromo(viewModel.PromoModel);
                    return(RedirectToAction("Edit", "Promo"));
                }
                else
                {
                    viewModel.PromoModel.PromoId     = int.Parse(promoId);
                    viewModel.PromoModel.ImageString = imageString;
                    return(View(viewModel));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dataService = null;
            }
        }
Ejemplo n.º 31
0
        public void SaveDoesNotModifyExtensionWhenForceCorrectExtensionRenameIsCleared()
        {
            // Arrange
            // Use rooted path so we by pass using HttpContext
            var specifiedOutputFile = @"x:\some-dir\foo.exe";
            string actualOutputFile = null;
            Action<string, byte[]> saveAction = (fileName, content) => { actualOutputFile = fileName; };

            // Act
            WebImage image = new WebImage(_BmpImageBytes);
            image.Save(GetContext(), saveAction, filePath: specifiedOutputFile, imageFormat: "jpg", forceWellKnownExtension: false);

            // Assert
            Assert.Equal(specifiedOutputFile, actualOutputFile);
        }
Ejemplo n.º 32
0
        public ActionResult Register(RegisterModel model)
        {
            int genNumber = randomInteger.Next(1234567890);

            model.RegistrationType = "Student";

            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    if (model.RegistrationType == "Student")
                    {
                        try
                        {
                            if (Request.Files.Count > 0)
                            {
                                HttpPostedFileBase file = Request.Files[0];
                                if (file.ContentLength > 0 && file.ContentType.ToUpper().Contains("JPEG") || file.ContentType.ToUpper().Contains("PNG"))
                                {
                                    WebImage img = new WebImage(file.InputStream);
                                    if (img.Width > 200)
                                    {
                                        img.Resize(200, 200, true, true);
                                    }
                                    string fileName = Path.Combine(Server.MapPath("~/Uploads/Items/"), Path.GetFileName(genNumber + file.FileName));
                                    img.Save(fileName);
                                    model.ImageUrl = fileName;
                                }
                                else
                                {
                                    ViewBag.SchoolId = new SelectList(db.Schools, "SchoolId", "SchoolName", model.SchoolId);
                                    return(View(model));
                                }
                            }
                            WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { EmailAddress = model.EmailAddress, PhoneNumber = model.PhoneNumber, RegistrationType = model.RegistrationType, ImageUrl = model.ImageUrl, Departmentid = model.DepartmentId, LevelId = model.Levelid, SurName = model.SurName, FirstName = model.FirstName, OtherNames = model.OtherNames, RegistrationNumber = model.RegistrationNumber, IsComplated = true });
                            WebSecurity.Login(model.UserName, model.Password);

                            if (!Roles.RoleExists("Student"))
                            {
                                Roles.CreateRole("Student");
                            }
                            Roles.AddUsersToRoles(new[] { model.UserName }, new[] { "Student" });
                            return(RedirectToAction("Index", "Profile"));
                        }
                        catch
                        {
                            ViewBag.SchoolId = new SelectList(db.Schools, "SchoolId", "SchoolName", model.SchoolId);
                            return(View(model));
                        }
                    }
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.SchoolId = new SelectList(db.Schools, "SchoolId", "SchoolName", model.SchoolId);
            return(View(model));
        }
Ejemplo n.º 33
0
        public void ResizePreservesResolution()
        {
            MemoryStream output = null;
            Action<string, byte[]> saveAction = (_, content) => { output = new MemoryStream(content); };

            WebImage image = new WebImage(_PngImageBytes);

            image.Resize(100, 50, preserveAspectRatio: true, preventEnlarge: true);

            image.Save(GetContext(), saveAction, @"x:\ResizePreservesResolution.jpg", "jpeg", forceWellKnownExtension: true);
            using (Image original = Image.FromStream(new MemoryStream(_PngImageBytes)))
            {
                using (Image modified = Image.FromStream(output))
                {
                    Assert.Equal(original.HorizontalResolution, modified.HorizontalResolution);
                    Assert.Equal(original.VerticalResolution, modified.VerticalResolution);
                }
            }
        }
Ejemplo n.º 34
0
        public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file)
        {
            //Check model state
            if (!ModelState.IsValid)
            {
                using (Db db = new Db())
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    return(View(model));
                }
            }

            //Make sure product name is unique
            using (Db db = new Db())
            {
                if (db.Products.Any(x => x.Name == model.Name))
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    ModelState.AddModelError("", "That product name is taken!");
                    return(View(model));
                }
            }


            //Declare product id
            int id;

            //Init and save productDTO
            using (Db db = new Db())
            {
                ProductDTO product = new ProductDTO();

                product.Name = model.Name;
                product.Slug = model.Name.Replace(" ", "-").ToLower();

                product.Description = model.Description;
                product.Price       = model.Price;
                product.CategoryId  = model.CategoryId;

                CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                product.CategoryName = catDTO.Name;

                db.Products.Add(product);
                db.SaveChanges();

                //Get the id
                id = product.Id;
            }


            //Set TempData message
            TempData["SM"] = "You have added a product!";

            #region Upload Image

            //Create necessary directories
            var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));


            var pathString1 = Path.Combine(originalDirectory.ToString(), "Products");
            var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
            var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");
            var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery");
            var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs");

            if (!Directory.Exists(pathString1))
            {
                Directory.CreateDirectory(pathString1);
            }

            if (!Directory.Exists(pathString2))
            {
                Directory.CreateDirectory(pathString2);
            }

            if (!Directory.Exists(pathString3))
            {
                Directory.CreateDirectory(pathString3);
            }

            if (!Directory.Exists(pathString4))
            {
                Directory.CreateDirectory(pathString4);
            }

            if (!Directory.Exists(pathString5))
            {
                Directory.CreateDirectory(pathString5);
            }

            //Check if a file was uploaded
            if (file != null && file.ContentLength > 0)
            {
                //Get file extension
                string ext = file.ContentType.ToLower();

                //Verify extension
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Db db = new Db())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "That image was not uploaded - wrong image extension!");
                        return(View(model));
                    }
                }

                //Init image name
                string imageName = file.FileName;

                //Save image name to DTO
                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;

                    db.SaveChanges();
                }

                //Set orginal and thumb image paths
                var path  = string.Format("{0}\\{1}", pathString2, imageName);
                var path2 = string.Format("{0}\\{1}", pathString3, imageName);


                //Save original
                file.SaveAs(path);

                //Create and save thumb
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }

            #endregion

            //Redirect

            return(RedirectToAction("AddProduct"));
        }
Ejemplo n.º 35
0
        public void SaveUpdatesFileNameOfWebImageWhenForcingWellKnownExtension()
        {
            // Arrange
            var context = GetContext();

            // Act
            WebImage image = new WebImage(context, _ => _JpgImageBytes, @"c:\images\foo.jpg");

            image.Save(context, (_, __) => { }, @"x:\1.exe", "jpg", forceWellKnownExtension: true);

            // Assert
            Assert.Equal(@"x:\1.exe.jpeg", image.FileName);
        }
Ejemplo n.º 36
0
        public async Task <ActionResult> ChangeProfilePicture(HttpPostedFileBase file)
        {
            UserProfilePhoto userP  = null;
            string           userId = User.Identity.GetUserId();
            var allowedExtensions   = new[] { ".Jpg", ".png", ".jpg", ".jpeg", ".JPG", ".GIF", ".Gif", ".gif" };
            var ext = Path.GetExtension(file.FileName);

            var retrievedUserPhoto = _applicationDbContext.UserProfilePhotos.SingleOrDefault(u => u.UserId == userId);

            if (retrievedUserPhoto == null)
            {
            }
            else
            {
                string userImageToDelete = retrievedUserPhoto.ImageName;
                string path = Request.MapPath("~/ProfilePhoto/" + userImageToDelete);
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }
            }

            if (file != null && allowedExtensions.Contains(ext))
            {
                userP = new UserProfilePhoto();
                string filename = null;
                //string filename = Guid.NewGuid() + Path.GetExtension(file.FileName);
                //string filename = Guid.NewGuid() + file.FileName;

                WebImage img = new WebImage(file.InputStream);
                if (img.Width > 120)
                {
                    img.Resize(120, 44);
                }
                int length = file.FileName.IndexOf(".");
                if (length > 0)
                {
                    filename = file.FileName.Substring(0, length);
                }

                string randFileName = Guid.NewGuid() + Path.GetExtension(filename);
                //string filename = file.FileName.Substring(file.FileName.IndexOf(".") + 1).Trim();
                img.Save(Path.Combine(Server.MapPath("~/ProfilePhoto"), filename));


                if (retrievedUserPhoto == null)
                {
                    userP.UserId      = User.Identity.GetUserId();
                    userP.ImageName   = filename + Path.GetExtension(img.FileName);
                    userP.DateCreated = DateTime.UtcNow;

                    _applicationDbContext.UserProfilePhotos.Add(userP);
                    await _applicationDbContext.SaveChangesAsync();

                    return(RedirectToAction("Index", new { Message = ManageMessageId.AddProfileImage }));
                }
                else
                {
                    var userPictureToUpdate = _applicationDbContext.UserProfilePhotos
                                              .Where(i => i.UserId == userId)
                                              .Single();
                    if (TryUpdateModel(userPictureToUpdate, "",
                                       new string[] { "UserProfilePhotoId", "UserId", "ImageName", "DateCreated" }))
                    {
                        try
                        {
                            userPictureToUpdate.ImageName = filename + Path.GetExtension(img.FileName);
                            _applicationDbContext.Entry(userPictureToUpdate).State = EntityState.Modified;
                            await _applicationDbContext.SaveChangesAsync();

                            return(RedirectToAction("Index", new { Message = ManageMessageId.AddProfileImage }));
                        }
                        catch (Exception /* dex */)
                        {
                            //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
                            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, do contact us.");
                        }
                    }
                }
            }
            ModelState.AddModelError("", "Failed upload valid photo");
            return(View());
        }
Ejemplo n.º 37
0
        public void SaveKeepsNameIfFormatIsUnchanged()
        {
            // Arrange
            string imagePath = @"x:\images\foo.jpg";
            var context = GetContext();

            // Act
            WebImage image = new WebImage(context, _ => _JpgImageBytes, imagePath);

            image.Save(context, (_, __) => { }, imagePath, "jpg", forceWellKnownExtension: true);

            // Assert
            Assert.Equal(@"x:\images\foo.jpg", image.FileName);
        }
Ejemplo n.º 38
0
        public static bool SaveImage(int id, HttpPostedFileBase file, string folderName)
        {
            var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", HttpContext.Current.Server.MapPath(@"\")));

            var pathString1 = Path.Combine(originalDirectory.ToString(), folderName);
            var pathString2 = Path.Combine(originalDirectory.ToString(), folderName + "\\" + id.ToString());

            if (!Directory.Exists(pathString1))
            {
                Directory.CreateDirectory(pathString1);
            }

            if (!Directory.Exists(pathString2))
            {
                Directory.CreateDirectory(pathString2);
            }

            if (file != null && file.ContentLength > 0)
            {
                // Get file extension
                string ext = file.ContentType.ToLower();

                // Verify extension
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    return(false);
                }

                // Set original and thumb image paths
                var path = string.Format("{0}\\{1}", pathString2, file.FileName);

                // Save original
                file.SaveAs(path);

                #region AdditionalFolders
                //Only for Products

                var pathString3 = Path.Combine(originalDirectory.ToString(), folderName + "\\" + id.ToString() + "\\Thumbs");
                var pathString4 = Path.Combine(originalDirectory.ToString(), folderName + "\\" + id.ToString() + "\\Gallery");
                var pathString5 = Path.Combine(originalDirectory.ToString(), folderName + "\\" + id.ToString() + "\\Gallery\\Thumbs");

                if (!Directory.Exists(pathString3))
                {
                    Directory.CreateDirectory(pathString3);
                }

                if (!Directory.Exists(pathString4))
                {
                    Directory.CreateDirectory(pathString4);
                }

                if (!Directory.Exists(pathString5))
                {
                    Directory.CreateDirectory(pathString5);
                }

                var path2 = string.Format("{0}\\{1}", pathString3, file.FileName);
                // Create and save thumb
                WebImage img = new WebImage(file.InputStream);
                img.Resize(150, 150);
                img.Save(path2);

                #endregion
            }

            return(true);
        }
Ejemplo n.º 39
0
        public void SaveThrowsWhenPathIsNull()
        {
            Action<string, byte[]> saveAction = (path, content) => { };

            // this constructor will not set path
            byte[] originalContent = _BmpImageBytes;
            WebImage image = new WebImage(originalContent);

            Assert.ThrowsArgumentNullOrEmptyString(
                () => image.Save(GetContext(), saveAction, filePath: null, imageFormat: null, forceWellKnownExtension: true),
                "filePath");
        }
Ejemplo n.º 40
0
        public ActionResult AddStudent(StudentVM model, HttpPostedFileBase file)
        {
            if (!ModelState.IsValid)
            {
                using (Db db = new Db())
                {
                    model.Cohorts = new SelectList(db.Cohorts.ToList(), "Id", "Name");
                    return(View(model));
                }
            }

            using (Db db = new Db())
            {
                if (db.Student.Any(x => x.FirstName == model.FirstName))
                {
                    model.Cohorts = new SelectList(db.Cohorts.ToList(), "Id", "Name");
                    ModelState.AddModelError("", "Sorry! That student name is taken!");
                    return(View(model));
                }
            }

            int id;

            using (Db db = new Db())
            {
                StudentDTO student = new StudentDTO();

                student.FirstName = model.FirstName;
                student.LastName  = model.LastName;
                student.Root      = model.FirstName.Replace(" ", "-").ToLower();
                student.CohortId  = model.CohortId;

                CohortDTO catDTO = db.Cohorts.FirstOrDefault(x => x.Id == model.CohortId);
                student.CohortName = catDTO.Name;

                db.Student.Add(student);
                //db.SaveChanges();

                id = student.Id;
            }

            TempData["SM"] = "Successfully added a student!";

            #region Upload Image

            var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

            var pathString1 = Path.Combine(originalDirectory.ToString(), "Products");
            var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
            var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");
            var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery");
            var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs");

            if (!Directory.Exists(pathString1))
            {
                Directory.CreateDirectory(pathString1);
            }

            if (!Directory.Exists(pathString2))
            {
                Directory.CreateDirectory(pathString2);
            }

            if (!Directory.Exists(pathString3))
            {
                Directory.CreateDirectory(pathString3);
            }

            if (!Directory.Exists(pathString4))
            {
                Directory.CreateDirectory(pathString4);
            }

            if (!Directory.Exists(pathString5))
            {
                Directory.CreateDirectory(pathString5);
            }

            if (file != null && file.ContentLength > 0)
            {
                string ext = file.ContentType.ToLower();

                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Db db = new Db())
                    {
                        model.Cohorts = new SelectList(db.Cohorts.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "ERROR: The image was not uploaded - wrong image extension.");
                        return(View(model));
                    }
                }

                string imageName = file.FileName;

                using (Db db = new Db())
                {
                    StudentDTO dto = db.Student.Find(id);
                    if (dto != null)
                    {
                        dto.ImageName = imageName;
                    }

                    db.SaveChanges();
                }

                var path  = string.Format("{0}\\{1}", pathString2, imageName);
                var path2 = string.Format("{0}\\{1}", pathString3, imageName);

                file.SaveAs(path);

                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }

            #endregion

            return(RedirectToAction("AddStudent"));
        }
Ejemplo n.º 41
0
        public void SaveUsesOriginalFormatForStreamsWhenNoFormatIsSpecified()
        {
            // Arrange
            // Use rooted path so we by pass using HttpContext
            var specifiedOutputFile = @"x:\some-dir\foo.jpg";
            string actualOutputFile = null;
            Action<string, byte[]> saveAction = (fileName, content) => { actualOutputFile = fileName; };

            // Act
            WebImage image = new WebImage(_PngImageBytes);
            image.Save(GetContext(), saveAction, filePath: specifiedOutputFile, imageFormat: null, forceWellKnownExtension: true);

            // Assert
            Assert.Equal(Path.GetExtension(actualOutputFile), ".png");
        }
Ejemplo n.º 42
0
        public ActionResult EditProduct(ProductVM model, IEnumerable <HttpPostedFileBase> file)
        {
            int    id          = model.Id;
            var    checkFile   = file.First();
            string styleNumber = model.StyleNumber.ToLower();

            using (Db db = new Db())
            {
                #region Validation
                bool checkUnique = db.Products.Where(p => p.Id != id).Any(p => p.StyleNumber == styleNumber);

                if (!ModelState.IsValid || checkUnique)
                {
                    GetSomeDataForValidate(model, true);

                    if (checkUnique)
                    {
                        ModelState.AddModelError("", "That Style Number is taken, enter unique number");
                    }
                    return(View(model));
                }

                if (checkFile != null)
                {
                    bool checkContType = file.All(f => (f.ContentType.ToLower() == "image/jpeg") || (f.ContentType.ToLower() == "image/jpg") || (f.ContentType.ToLower() == "image/png"));
                    if (!checkContType)
                    {
                        GetSomeDataForValidate(model, true);
                        ModelState.AddModelError("", "The images were not uploaded, image extension must be jpeg, jpg or png");
                        return(View(model));
                    }
                }
                #endregion

                string     slug = model.Name.Replace(" ", "-") + "-" + styleNumber;
                ProductDTO dto  = db.Products.Find(id);
                dto.Name           = model.Name;
                dto.Slug           = slug.ToLower();
                dto.Description    = model.Description;
                dto.ManufacturerId = model.ManufacturerId;
                dto.StyleNumber    = styleNumber;
                dto.Price          = model.Price;
                if (checkFile != null)
                {
                    dto.ImageName = file.First().FileName;
                }
                dto.Categories = db.Categories.Where(ca => model.SelectedCategoryIds.Contains(ca.Id)).ToList();
                db.SaveChanges();
            }

            #region Upload images

            if (checkFile != null)
            {
                var originalDir = Path.Combine($"{Server.MapPath(@"\")}Images\\Uploads\\Products", id.ToString(), "Gallery");
                if (Directory.Exists(originalDir))
                {
                    var originalImages = Directory.EnumerateFiles(originalDir);
                    if (originalImages.Count() > 0)
                    {
                        foreach (var path in originalImages)
                        {
                            try
                            {
                                System.IO.File.Delete(path);
                            }
                            catch
                            {
                                TempData["SM"] = "You have edited the product";
                                TempData["EM"] = "But the images failed to save";
                                return(RedirectToAction("EditProduct", id));
                            }
                        }
                    }
                    foreach (var f in file)
                    {
                        try
                        {
                            f.SaveAs(string.Format($"{originalDir}\\{f.FileName}"));
                        }
                        catch
                        {
                            TempData["SM"] = "You have edited the product";
                            TempData["EM"] = "But the images failed to save";
                            return(RedirectToAction("EditProduct", id));
                        }
                    }
                }
                var thumbsDir = Path.Combine($"{Server.MapPath(@"\")}Images\\Uploads\\Products", id.ToString(), "Gallery\\Thumbs");
                if (Directory.Exists(thumbsDir))
                {
                    var thumbsImages = Directory.EnumerateFiles(thumbsDir);
                    if (thumbsImages.Count() > 0)
                    {
                        foreach (var path in thumbsImages)
                        {
                            try
                            {
                                System.IO.File.Delete(path);
                            }
                            catch
                            {
                                TempData["SM"] = "You have edited the product";
                                TempData["EM"] = "But the images failed to save";
                                return(RedirectToAction("EditProduct", id));
                            }
                        }
                    }
                    WebImage img;
                    foreach (var f in file)
                    {
                        img = new WebImage(f.InputStream);
                        img.Resize(321, 321).Crop(1, 1);
                        try
                        {
                            img.Save(string.Format($"{thumbsDir}\\{f.FileName}"));
                        }
                        catch
                        {
                            TempData["SM"] = "You have edited the product";
                            TempData["EM"] = "But the images failed to save";
                            return(RedirectToAction("EditProduct", id));
                        }
                    }
                }
            }

            #endregion
            TempData["SM"] = "You have edited the product";
            return(RedirectToAction("Products"));
        }