Beispiel #1
0
        public ActionResult CreateGame(CreateGameViewModel model, HttpPostedFileBase imageFile)
        {
            string fileName = Guid.NewGuid().ToString() + ".jpg";

            string image = Server.MapPath(Constants.ImagePath) + "\\" + fileName;

            using (Bitmap img = new Bitmap(imageFile.InputStream))
            {
                Bitmap saveImage = ImageWorker.CreateImage(img, 400, 400);
                if (saveImage != null)
                {
                    saveImage.Save(image, ImageFormat.Jpeg);
                    // Save game with name image in Db
                    _context.Games.Add(new Game
                    {
                        Developer = model.Developer,
                        Image     = fileName,
                        Name      = model.Name,
                        Price     = model.Price
                    });
                    _context.SaveChanges();
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
        public JsonResult UploadImageDecription(HttpPostedFileBase file)
        {
            string link     = string.Empty;
            string filename = Guid.NewGuid().ToString() + ".jpg";
            string image    = Server.MapPath(Constants.ProductDescriptionPath) + filename;

            try
            {
                // The Complete method commits the transaction. If an exception has been thrown,
                // Complete is not  called and the transaction is rolled back.
                Bitmap imgCropped = new Bitmap(file.InputStream);
                var    saveImage  = ImageWorker.CreateImage(imgCropped, 450, 450);
                if (saveImage == null)
                {
                    throw new Exception("Error save image");
                }
                saveImage.Save(image, ImageFormat.Jpeg);
                link = Url.Content(Constants.ProductDescriptionPath) + filename;
                ProductDescriptionImage pImage = new ProductDescriptionImage()
                {
                    Name = filename
                };
                _context.ProductDescriptionImages.Add(pImage);
                _context.SaveChanges();
            }
            catch (Exception)
            {
                if (System.IO.File.Exists(image))
                {
                    System.IO.File.Delete(image);
                }
            }

            return(Json(new { link, filename }));
        }
Beispiel #3
0
        public ActionResult Edit(StudentViewModel el, HttpPostedFileBase file)
        {
            Student st = _context.Students.Find(el.Id);

            st.ApplicationUser.Email = el.Email;
            st.Age   = el.Age;
            st.Phone = el.Phone;
            st.Id    = el.Id;

            st.Image = el.Image;

            if (file != null)
            {
                string filename = Guid.NewGuid().ToString() + ".jpg";
                string image    = Server.MapPath(Constants.ImagePath) + "\\" + filename;

                using (Bitmap bmp = new Bitmap(file.InputStream))
                {
                    Bitmap saveImage = ImageWorker.CreateImage(bmp, 200, 120);
                    if (saveImage != null)
                    {
                        saveImage.Save(image);
                        st.Image = filename;
                    }
                }
            }

            _context.SaveChanges();
            return(RedirectToAction("Index"));
        }
Beispiel #4
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl, HttpPostedFileBase ImgFile)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

                    if (result.Succeeded)
                    {
                        string fileName = Guid.NewGuid().ToString() + ".jpg";

                        string image = Server.MapPath(UniversityManager.Helpers.Constants.ImagePath) + "//" + fileName;

                        using (Bitmap img = new Bitmap(ImgFile.InputStream))
                        {
                            Bitmap saveImg = ImageWorker.CreateImage(img, 400, 400);
                            if (saveImg != null)
                            {
                                saveImg.Save(image, ImageFormat.Jpeg);
                                _context.userAdditionalInfos.Add(new Models.EF.UserAdditionalInfo()
                                {
                                    FullName = model.FullName,
                                    Address  = model.Address,
                                    Image    = fileName,
                                    GroupId  = int.Parse(model.GroupId),
                                    Id       = user.Id
                                });
                                _context.SaveChanges();
                            }
                        }
                        UserManager.AddToRole(user.Id, "Student");
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
        public ResultDTO Uploadfile([FromRoute] string id, [FromForm(Name = "file")] IFormFile image)
        {
            string Filename = Guid.NewGuid().ToString() + ".jpg";
            string path     = _appEnvironment.WebRootPath + @"\Images";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = path + @"\" + Filename;
            if (image == null)
            {
                return(new ResultErrorDTO
                {
                    Message = "File is null",
                    Status = 405,
                    Errors = null
                });
            }
            if (image.Length == 0)
            {
                return(new ResultErrorDTO
                {
                    Message = "File is empty",
                    Status = 405,
                    Errors = null
                });
            }
            using (Bitmap b = new Bitmap(image.OpenReadStream()))
            {
                Bitmap SaveImage = ImageWorker.CreateImage(b, 400, 300);

                if (SaveImage != null)
                {
                    SaveImage.Save(path, ImageFormat.Jpeg);
                    Game game = _context.Games.Find(id);
                    if (game.ImageURL != null)
                    {
                        System.IO.File.Delete(_appEnvironment.WebRootPath + @"\Images" + game.ImageURL);
                    }
                    _context.Games.Find(id).ImageURL = Filename;
                    _context.SaveChanges();

                    return(new ResultDTO
                    {
                        Message = "File is  saved",
                        Status = 200
                    });
                }
                else
                {
                    return(new ResultErrorDTO
                    {
                        Message = "File is not saved",
                        Status = 405,
                        Errors = null
                    });
                }
            }
        }
Beispiel #6
0
        public IActionResult Create([FromBody] CountryAddViewModel model)
        {
            var country = _context.Countries
                          .SingleOrDefault(c => c.Name == model.Name);

            if (country != null)
            {
                return(BadRequest(new { invalid = "Така країна уже є в БД!" }));
            }

            string fileDestDir = _env.ContentRootPath;

            fileDestDir = Path.Combine(fileDestDir, "Bigimot");
            string imageName = Path.GetRandomFileName() + ".jpg";

            var bitmap = model.Image.Split(',')[1].FromBase64StringToImage();

            var outbtmp = ImageWorker.CreateImage(bitmap, 100, 100);

            outbtmp.Save(Path.Combine(fileDestDir, imageName), ImageFormat.Jpeg);
            //bitmap.Save(Path.Combine(fileDestDir,imageName), ImageFormat.Jpeg);

            country = new Country
            {
                Name      = model.Name,
                FlagImage = model.FlagImage
            };
            _context.Countries.Add(country);
            _context.SaveChanges();
            return(Ok(new CountryViewModel
            {
                Id = country.Id,
                Name = country.Name
            }));
        }
Beispiel #7
0
        public ResultDTO UploadImage([FromForm(Name = "file")] IFormFile uploadedImage)
        {
            string fileName = Guid.NewGuid().ToString() + ".jpg";
            string path     = _appEnvironment.WebRootPath + @"\Images\" + fileName;

            if (uploadedImage == null)
            {
                return new ResultDTO
                       {
                           Status = 400,
                           Errors = new List <string> {
                               "Не вдалося завантажити файл"
                           }
                       }
            }
            ;
            if (uploadedImage.Length == 0)
            {
                return new ResultDTO
                       {
                           Status = 400,
                           Errors = new List <string> {
                               "Файл порожній"
                           }
                       }
            }
            ;
            try
            {
                using (Bitmap bmp = new Bitmap(uploadedImage.OpenReadStream()))
                {
                    var saveImage = ImageWorker.CreateImage(bmp, 400, 365);
                    int idProduct = (from v in _context.Products orderby v.Id descending select v).FirstOrDefault().Id;
                    if (saveImage != null)
                    {
                        saveImage.Save(path, ImageFormat.Jpeg);
                        var product = _context.Products.Find(idProduct);

                        _context.Products.Find(idProduct).Image = fileName;
                        _context.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                return(new ResultDTO
                {
                    Status = 400,
                    Errors = new List <string> {
                        "Не вдалося завантажити файл"
                    },
                    Message = ex.InnerException.Message
                });
            }
            return(new ResultDTO
            {
                Status = 200
            });
        }
Beispiel #8
0
        public ContentResult UploadBase64(string base64image)
        {
            string filename   = Guid.NewGuid().ToString() + ".jpg";
            string imageBig   = Server.MapPath(Constants.ProductImagePath) + filename;
            string imageSmall = Server.MapPath(Constants.ProductThumbnailPath) + filename;
            string json       = null;

            try
            {
                // The Complete method commits the transaction. If an exception has been thrown,
                // Complete is not  called and the transaction is rolled back.
                Bitmap imgCropped = base64image.FromBase64StringToBitmap();
                var    saveImage  = ImageWorker.CreateImage(imgCropped, 300, 300);
                if (saveImage == null)
                {
                    throw new Exception("Error save image");
                }

                saveImage.Save(imageBig, ImageFormat.Jpeg);

                var saveImageIcon = ImageWorker.CreateImage(imgCropped, 32, 32);
                if (saveImageIcon == null)
                {
                    throw new Exception("Error save image");
                }
                saveImageIcon.Save(imageSmall, ImageFormat.Jpeg);

                var productImage = new ProductImage {
                    FileName = filename
                };
                _context.ProductImages.Add(productImage);
                _context.SaveChanges();

                json = JsonConvert.SerializeObject(new
                {
                    imagePath = Url.Content(Constants.ProductImagePath) + filename,
                    id        = productImage.Id
                });
            }
            catch (Exception)
            {
                json = JsonConvert.SerializeObject(new
                {
                    imagePath = ""
                });
                if (System.IO.File.Exists(imageSmall))
                {
                    System.IO.File.Delete(imageSmall);
                }
                if (System.IO.File.Exists(imageBig))
                {
                    System.IO.File.Delete(imageBig);
                }
            }
            return(Content(json, "application/json"));
        }
        public async Task <ActionResult> Register(RegisterViewModel model, HttpPostedFileBase imageFile)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    string fileName = Guid.NewGuid().ToString() + ".jpg";
                    string image    = Server.MapPath(Constants.ImagePath) + "\\" + fileName;

                    using (Bitmap bmp = new Bitmap(imageFile.InputStream))
                    {
                        Bitmap saveImage = ImageWorker.CreateImage(bmp, 400, 400);
                        if (saveImage != null)
                        {
                            saveImage.Save(image);


                            UserManager.AddToRole(user.Id, "User");
                            Student st = new Student()
                            {
                                ApplicationUser = ctx.Users.FirstOrDefault(x => x.Email == model.Email),
                                FirstName       = model.FirstName,
                                SecondName      = model.SecondName,
                                Image           = fileName
                            };
                            ctx.Students.Add(st);
                            ctx.SaveChanges();
                        }
                    }


                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "User", new { area = "User" }));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Beispiel #10
0
        public ResultDTO UploadImage([FromRoute] string id, [FromForm(Name = "file")] IFormFile image)
        {
            string filename = Guid.NewGuid().ToString() + ".jpg";
            string path     = _webHostEnvironment.WebRootPath + @"\Images";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = path + @"\" + filename;
            if (image == null)
            {
                return(new ResultDTO
                {
                    Status = 505,
                    Message = "File is empty"
                });
            }
            if (image.Length == 0)
            {
                return(new ResultDTO
                {
                    Message = "File is empty",
                    Status = 506
                });
            }
            using (Bitmap b = new Bitmap(image.OpenReadStream()))
            {
                Bitmap savedImage = ImageWorker.CreateImage(b, 400, 360);
                if (savedImage != null)
                {
                    savedImage.Save(path, ImageFormat.Jpeg);
                    Meme meme = _context.Memes.Find(id);
                    meme.Image = filename;
                    _context.SaveChanges();
                    return(new ResultDTO
                    {
                        Message = "Image saved",
                        Status = 200
                    });
                }
                else
                {
                    return(new ResultDTO
                    {
                        Message = "Uploading ERROR",
                        Status = 506
                    });
                }
            };
        }
Beispiel #11
0
        public async Task <ActionResult> Register(RegisterViewModel model, HttpPostedFileBase ImgFile)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    string fileName = Guid.NewGuid().ToString() + ".jpg";

                    string image = Server.MapPath(UniversityManager.Helpers.Constants.ImagePath) + "//" + fileName;

                    using (Bitmap img = new Bitmap(ImgFile.InputStream))
                    {
                        Bitmap saveImg = ImageWorker.CreateImage(img, 400, 400);
                        if (saveImg != null)
                        {
                            saveImg.Save(image, ImageFormat.Jpeg);
                            _context.userAdditionalInfos.Add(new Models.EF.UserAdditionalInfo()
                            {
                                FullName = model.FullName,
                                Address  = model.Address,
                                Image    = fileName,
                                GroupId  = int.Parse(model.GroupId),
                                Id       = user.Id
                            });
                            _context.SaveChanges();
                        }
                    }
                    UserManager.AddToRole(user.Id, "Student");
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

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

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Beispiel #12
0
        public JsonResult UploadImageDescription(HttpPostedFileBase file)
        {
            //string pathServer = ConfigurationManager.AppSettings["UserImagePath"];
            //string path = Server.MapPath(pathServer);

            //var image = Guid.NewGuid().ToString() + ".jpg";
            //string savepath = path + image;
            //Bitmap imageBig = ImageWorker.CreateImage(file, 1100, 1200);
            //imageBig.Save(savepath, ImageFormat.Jpeg);

            string link     = string.Empty;
            var    filename = Guid.NewGuid().ToString() + ".jpg";
            string image    = Server.MapPath(Constants.ProductDescriptionPath) + filename;

            try
            {
                using (Bitmap btn = new Bitmap(file.InputStream))
                {
                    var saveImage = ImageWorker.CreateImage(btn, 450, 450);
                    if (saveImage != null)
                    {
                        using (TransactionScope scope = new TransactionScope())
                        {
                            var pdImage = new ProductDescriptionImage
                            {
                                Name = filename
                            };
                            _context.ProductDescriptionImages.Add(pdImage);
                            _context.SaveChanges();
                            saveImage.Save(image, ImageFormat.Jpeg);
                            link = Url.Content(Constants.ProductDescriptionPath) + filename;
                            scope.Complete();
                        }
                    }
                }
            }
            catch
            {
                if (System.IO.File.Exists(image))
                {
                    System.IO.File.Delete(image);
                }
                link = string.Empty;
            }

            return(Json(new { link, filename }));
        }
        public async System.Threading.Tasks.Task <ActionResult> CreateTeacher(RegisterTeacherViewModel model, HttpPostedFileBase ImgFile)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    string fileName = Guid.NewGuid().ToString() + ".jpg";

                    string image = Server.MapPath(UniversityManager.Helpers.Constants.ImagePath) + "//" + fileName;

                    using (Bitmap img = new Bitmap(ImgFile.InputStream))
                    {
                        Bitmap saveImg = ImageWorker.CreateImage(img, 400, 400);
                        if (saveImg != null)
                        {
                            saveImg.Save(image, ImageFormat.Jpeg);
                            _ctx.TeacherAdditionalInfos.Add(new Models.EF.TeacherAdditionalInfo()
                            {
                                FullName = model.FullName,
                                Address  = model.Address,
                                Image    = fileName,
                                Id       = user.Id,
                                Skills   = model.Skills
                            });
                            _ctx.SaveChanges();
                        }
                    }
                    UserManager.AddToRole(user.Id, "Teacher");
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    return(RedirectToAction("Index", "Home", new { area = "" }));
                }
                AddErrors(result);
            }

            return(View(model));
        }
Beispiel #14
0
        private void ConvertImage(int size)
        {
            var    imageFolderSave = "uploads";
            Bitmap bmpOrigin       = new Bitmap(image);
            var    imageName       = Guid.NewGuid().ToString() + ".jpg";
            var    imageSave       = ImageWorker.CreateImage(bmpOrigin, size, size);

            if (imageSave == null)
            {
                throw new Exception("Проблема обробки фото");
            }
            else
            {
                MessageBox.Show(imageSave.Height.ToString() + " x " + imageSave.Width.ToString(), "Размер изображения");
            }

            var imageSaveEnd = System.IO.Path.Combine(imageFolderSave, imageName);

            imageSave.Save(imageSaveEnd, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
Beispiel #15
0
        public ActionResult Edit(OfferViewModel model)
        {
            string filename = string.Empty;

            if (model.SomeFile != null)
            {
                string link = string.Empty;
                filename = Guid.NewGuid().ToString() + ".jpg";
                string image = Server.MapPath(Constants.OfferImagePath) +
                               filename;
                using (Bitmap bmp = new Bitmap(model.SomeFile.InputStream))
                {
                    var saveImage = ImageWorker.CreateImage(bmp, 450, 450);
                    if (saveImage != null)
                    {
                        saveImage.Save(image, ImageFormat.Jpeg);
                        link = Url.Content(Constants.OfferImagePath) +
                               filename;
                    }
                }
            }
            var offer = _context.offers.FirstOrDefault(x => x.Id == model.OfferId);

            offer.Price        = model.Price;
            offer.Title        = model.Title;
            offer.UserID       = model.UserID;
            offer.UserPhone    = model.UserPhone;
            offer.Description  = model.Description;
            offer.Email        = model.Email;
            offer.categoryId   = model.categoryId;
            offer.CategoryName = Find_category(offer.categoryId);
            offer.cityId       = model.cityId;
            offer.cityName     = Find_city(offer.cityId);
            offer.IsVerified   = model.IsVerified;
            if (model.SomeFile != null)
            {
                offer.ImageName = filename;
            }
            _context.SaveChanges();
            return(RedirectToAction("Index", "Multi", new { id = User.Identity.GetUserId(), area = "" }));
        }
Beispiel #16
0
        public ActionResult Create(NewsViewModel model, HttpPostedFileBase someFile)
        {
            if (ModelState.IsValid)
            {
                string link     = string.Empty;
                string filename = Guid.NewGuid().ToString() + ".jpg";
                string image    = Server.MapPath(Constants.ProductImagePath) +
                                  filename;
                using (Bitmap bmp = new Bitmap(someFile.InputStream))
                {
                    var saveImage = ImageWorker.CreateImage(bmp, 450, 450);
                    if (saveImage != null)
                    {
                        saveImage.Save(image, ImageFormat.Jpeg);
                        link = Url.Content(Constants.ProductImagePath) +
                               filename;
                        string path = Url.Content(Constants.ProductImagePath);

                        var pdImage = new News
                        {
                            Image = path
                        };
                    }
                }
                _context.News.Add(new News
                {
                    Country     = model.Country,
                    Date        = model.Date,
                    Description = model.Description,
                    Time        = model.Time,
                    Title       = model.Title,
                    Image       = filename
                });
                _context.SaveChanges();
                return(RedirectToAction("Index", "Newsman"));
            }
            else
            {
                return(View(model));
            }
        }
Beispiel #17
0
        public ActionResult Create(CreateProductViewModel model, HttpPostedFileBase someFile)
        {
            // do something with someFile

            string link     = string.Empty;
            string filename = Guid.NewGuid().ToString() + ".jpg";
            string image    = Server.MapPath(Constants.ProductImagePath) +
                              filename;

            using (Bitmap bmp = new Bitmap(someFile.InputStream))
            {
                var saveImage = ImageWorker.CreateImage(bmp, 350, 350);
                if (saveImage != null)
                {
                    saveImage.Save(image, ImageFormat.Jpeg);

                    var pdImage = new Product
                    {
                        Name        = model.Name,
                        Price       = model.Price,
                        Photo       = filename,
                        Size        = model.Size,
                        Sale        = model.Sale,
                        Quantity    = model.Quantity,
                        Color       = model.Color,
                        Brand       = model.Brand,
                        Country     = model.Country,
                        Season      = model.Season,
                        Description = model.Description,
                        DataCreate  = DateTime.Now,
                        CategoryId  = model.CategoryId
                    };
                    _context.dbProduct.Add(pdImage);
                    _context.SaveChanges();
                    return(RedirectToAction("Index", "Product"));
                }
            }

            return(View(model));
        }
Beispiel #18
0
        public ActionResult Edit(StudentViewModel pt, HttpPostedFileBase imageFile)
        {
            var n = ctx.Groups.FirstOrDefault(x => x.Name == pt.GroupName);

            if (imageFile != null)
            {
                string fileName = Guid.NewGuid().ToString() + ".jpg";
                string image    = Server.MapPath(Constants.ImagePath) + "\\" + fileName;
                using (Bitmap bmp = new Bitmap(imageFile.InputStream))
                {
                    Bitmap saveImage = ImageWorker.CreateImage(bmp, 400, 400);
                    if (saveImage != null)
                    {
                        Models.Entity.Models.Student p = ctx.Students.Find(pt.Id);
                        p.Id                          = pt.Id;
                        p.FirstName                   = pt.FirstName;
                        p.SecondName                  = pt.SecondName;
                        p.ApplicationUser.Email       = pt.Email;
                        p.ApplicationUser.PhoneNumber = pt.PhoneNumber;
                        p.GroupId                     = n.Id;
                        p.Image                       = fileName;
                        ctx.SaveChanges();
                    }
                }
            }
            else
            {
                Models.Entity.Models.Student p = ctx.Students.Find(pt.Id);
                p.Id                          = pt.Id;
                p.FirstName                   = pt.FirstName;
                p.SecondName                  = pt.SecondName;
                p.ApplicationUser.Email       = pt.Email;
                p.ApplicationUser.PhoneNumber = pt.PhoneNumber;
                p.GroupId                     = n.Id;
                p.Image                       = p.Image;
                ctx.SaveChanges();
            }
            return(RedirectToAction("GetAllGroups"));
        }
        public ActionResult Create(GameCreateViewModel viewModel, HttpPostedFileBase imageFile)
        {
            if (ModelState.IsValid)
            {
                string filename      = Guid.NewGuid().ToString() + ".jpg";
                string FullPathImage = Server.MapPath(Config.ProductImagePath) + "\\" + filename;

                using (Bitmap bmp = new Bitmap(imageFile.InputStream))
                {
                    var readyImage = ImageWorker.CreateImage(bmp, 450, 450);
                    if (readyImage != null)
                    {
                        readyImage.Save(FullPathImage, ImageFormat.Jpeg);
                        var game = mapper.Map <Game>(viewModel);
                        game.Image = filename;
                        gameService.AddGame(game);
                        return(RedirectToAction("Index"));
                    }
                }
            }
            return(Create());
        }
Beispiel #20
0
        public UserViewModel ChageUserImage(string userName, string image)
        {
            var user = _context.Users.SingleOrDefault(x => x.UserName == userName);

            if (user == null)
            {
                throw new RestException(HttpStatusCode.NotFound);
            }

            string filename = Guid.NewGuid().ToString() + ".jpg";
            string path     = Path.Combine(Directory.GetCurrentDirectory(), "ProfileImages");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = Path.Combine(path, filename);
            if (string.IsNullOrEmpty(image))
            {
                return(null);
            }

            using (Bitmap b = ImageWorker.Base64StringToBitmap(image))
            {
                Bitmap savedImage = ImageWorker.CreateImage(b, 400, 360);
                if (savedImage != null)
                {
                    savedImage.Save(path, ImageFormat.Jpeg);
                    user.Image = filename;
                    _context.SaveChanges();
                    return(null);
                }
                else
                {
                    return(null);
                }
            };
        }
Beispiel #21
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            var user = _context.Users
                       .SingleOrDefault(p => p.Id == _id);

            user.UserName = txtNameUser.Text;
            user.Email    = txtEmail.Text;

            var role = _context.Roles
                       .SingleOrDefault(p => p.Id == _id);

            role.Name = txtNameRole.Text;


            if (!string.IsNullOrEmpty(fileSelected))
            {
                string ext          = Path.GetExtension(fileSelected);
                string fileName     = Path.GetFileNameWithoutExtension(fileSelected) + ext;
                string fileSavePath = Path.Combine(Directory.GetCurrentDirectory(), "images", fileName);


                //if (File.Exists(fileName))
                //{
                /// <summary>
                /// видалення старого фото із системи при оновлені
                /// </summary>
                File.Delete(oldPhoto);
                //}
                var bmp = ImageWorker.CreateImage(
                    new Bitmap(Image.FromFile(fileSelected)), 75, 75);
                bmp.Save(fileSavePath, ImageFormat.Jpeg);
                user.Image = fileName;
            }

            _context.SaveChanges();
            DialogResult = DialogResult.OK;
        }
Beispiel #22
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            var post = _context.Posts
                       .SingleOrDefault(p => p.Id == _id);

            post.CategoryId = (cbCategory.SelectedItem as Category).Id;
            post.Title      = txtTitle.Text;
            if (!string.IsNullOrEmpty(fileSelected))
            {
                string ext          = Path.GetExtension(fileSelected);
                string fileName     = Path.GetRandomFileName() + ext;
                string fileSavePath = Path.Combine(Directory.GetCurrentDirectory(),
                                                   "images", fileName);
                var bmp = ImageWorker.CreateImage(
                    new Bitmap(Image.FromFile(fileSelected)), 75, 75);

                bmp.Save(fileSavePath, ImageFormat.Jpeg);
                //File.Copy(fileSelected, fileSavePath);
                post.Image = fileName;
            }

            _context.SaveChanges();
            this.DialogResult = DialogResult.OK;
        }
Beispiel #23
0
        public JsonResult UploadImageDecription(HttpPostedFileBase file)
        {
            string link     = string.Empty;
            string filename = Guid.NewGuid().ToString() + ".jpg";
            string image    = Server.MapPath(Constants.ProductDescriptionPath) +
                              filename;

            try
            {
                using (Bitmap bmp = new Bitmap(file.InputStream))
                {
                    var saveImage = ImageWorker.CreateImage(bmp, 450, 450);
                    if (saveImage != null)
                    {
                        saveImage.Save(image, ImageFormat.Jpeg);
                        link = Url.Content(Constants.ProductDescriptionPath) +
                               filename;
                        var pdImage = new ProductDescriptionImage
                        {
                            Name = filename
                        };
                        _context.ProductDescriptionImages.Add(pdImage);
                        _context.SaveChanges();
                    }
                }
                string path = Url.Content(Constants.ProductDescriptionPath);
            }
            catch (Exception)
            {
                if (System.IO.File.Exists(image))
                {
                    System.IO.File.Delete(image);
                }
            }
            return(Json(new { link, filename }));
        }
Beispiel #24
0
        public IActionResult Create([FromBody] ClientAddVM client)
        {
            if (!ModelState.IsValid)
            {
                var errors = CustomValidator.GetErrorsByModel(ModelState);
                return(BadRequest(errors));
            }
            string dirName     = "images";
            string dirPathSave = Path.Combine(dirName, client.UniqueName);

            if (!Directory.Exists(dirPathSave))
            {
                Directory.CreateDirectory(dirPathSave);
            }
            var    bmp       = client.Image.FromBase64StringToImage();
            var    imageName = client.UniqueName;
            string fileSave  = Path.Combine(dirPathSave, $"{imageName}");

            var bmpOrigin = new System.Drawing.Bitmap(bmp);

            string[] imageNames = { $"50_" + imageName + ".jpg",
                                    $"100_" + imageName + ".jpg",
                                    $"300_" + imageName + ".jpg",
                                    $"600_" + imageName + ".jpg",
                                    $"1280_" + imageName + ".jpg" };

            Bitmap[] imageSave = { ImageWorker.CreateImage(bmpOrigin,   50,  50),
                                   ImageWorker.CreateImage(bmpOrigin,  100, 100),
                                   ImageWorker.CreateImage(bmpOrigin,  300, 300),
                                   ImageWorker.CreateImage(bmpOrigin,  600, 600),
                                   ImageWorker.CreateImage(bmpOrigin, 1280, 1280) };

            for (int i = 0; i < imageNames.Count(); i++)
            {
                var imageSaveEnd = System.IO.Path.Combine(dirPathSave, imageNames[i]);
                imageSave[i].Save(imageSaveEnd, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            var str    = client.Phone;
            var regex  = @"\+38\d{1}\(\d{2}\)\d{3}\-\d{2}\-\d{2}";
            var str2   = client.Name;
            var regex2 = @"^[A-Za-z-а-яА-Я]+$";
            var str3   = client.Email;
            var regex3 = @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$";
            var match  = Regex.Match(str, regex);
            var match2 = Regex.Match(str2, regex2);
            var match3 = Regex.Match(str3, regex3);

            if (!match.Success)
            {
                return(BadRequest(new { Phone = "issue" }));
            }
            if (!match2.Success)
            {
                return(BadRequest(new { Name = "issue" }));
            }
            if (!match3.Success)
            {
                return(BadRequest(new { Email = "issue" }));
            }

            var cl = _context.Clients.FirstOrDefault(p => p.Email == client.Email);

            if (cl != null)
            {
                return(BadRequest(new { Email = "Такий email вже існує!" }));
            }
            var cli = _context.Clients.FirstOrDefault(p => p.Phone == client.Phone);

            if (cli != null)
            {
                return(BadRequest(new { Phone = "Такий номер вже існує!" }));
            }
            //var fileDestDir = _env.ContentRootPath;
            //string dirName = _configuration.GetValue<string>("ImagesPath");
            ////Папка де зберігаються фотки
            //string dirPathSave = Path.Combine(fileDestDir, dirName);
            //if (!Directory.Exists(dirPathSave))
            //{
            //    Directory.CreateDirectory(dirPathSave);
            //}
            //var bmp = model.Image.FromBase64StringToImage();
            //var imageName = Path.GetRandomFileName() + ".jpg";
            //string fileSave = Path.Combine(dirPathSave, $"{imageName}");

            //bmp.Save(fileSave, ImageFormat.Jpeg);

            Client c = new Client
            {
                Name       = client.Name,
                Phone      = client.Phone,
                Email      = client.Email,
                UniqueName = client.UniqueName
            };

            _context.Clients.Add(c);
            _context.SaveChanges();
            return(Ok(c.Id));
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                //if (model.Image != null)
                //{
                //    string fileName = Guid.NewGuid()+".jpg";
                //    model.Image.SaveAs(Server.MapPath(ConfigurationManager.AppSettings["ImageUserPath"] + fileName));
                //}
                try
                {
                    using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                    {
                        var user = new ApplicationUser {
                            UserName = model.Email, Email = model.Email
                        };
                        var result = await UserManager.CreateAsync(user, model.Password);

                        if (result.Succeeded)
                        {
                            // The Complete method commits the transaction. If an exception has been thrown,
                            // Complete is not  called and the transaction is rolled back.
                            string base64image = model.ImageBase64;
                            Bitmap imgCropped  = base64image.FromBase64StringToBitmap();
                            var    saveImage   = ImageWorker.CreateImage(imgCropped, 300, 300);
                            if (saveImage == null)
                            {
                                throw new Exception("Error save image");
                            }

                            string path     = Server.MapPath(ConfigurationManager.AppSettings["ImageUserPath"]);
                            string filename = Guid.NewGuid().ToString() + ".jpg";
                            saveImage.Save(path + filename, ImageFormat.Jpeg);

                            var saveImageIcon = ImageWorker.CreateImage(imgCropped, 32, 32);
                            if (saveImageIcon == null)
                            {
                                throw new Exception("Error save image");
                            }
                            saveImageIcon.Save(path + "32_" + filename, ImageFormat.Jpeg);

                            UserProfile userProfile = new UserProfile
                            {
                                Id          = user.Id,
                                Image       = filename,
                                DateOfBirth = null,
                                Phone       = model.Phone
                            };
                            _userService.AddUserProfiles(userProfile);
                            //throw new Exception("Bad");


                            await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                            // Send an email with this link
                            // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                            // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                            // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                            // The Complete method commits the transaction. If an exception has been thrown,
                            // Complete is not  called and the transaction is rolled back.
                            scope.Complete();
                            return(RedirectToAction("Index", "Home"));
                        }
                        AddErrors(result);
                    }
                }
                catch (TransactionAbortedException ex)
                {
                    Debug.WriteLine("TransactionAbortedException Message: {0}", ex.Message);
                    ModelState.AddModelError("", string.Format("TransactionAbortedException Message: {0}", ex.Message));
                }
                catch (ApplicationException ex)
                {
                    Debug.WriteLine("ApplicationException Message: {0}", ex.Message);
                    ModelState.AddModelError("", string.Format("ApplicationException Message: {0}", ex.Message));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception Message: {0}", ex.Message);
                    ModelState.AddModelError("", string.Format("Exception Message: {0}", ex.Message));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Beispiel #26
0
        public IActionResult Create([FromBody] CarAddVM model)
        {
            if (!ModelState.IsValid)
            {
                var errors = CustomValidator.GetErrorsByModel(ModelState);
                return(BadRequest(errors));
            }
            string dirName     = "images";
            string dirPathSave = Path.Combine(dirName, model.UniqueName);

            if (!Directory.Exists(dirPathSave))
            {
                Directory.CreateDirectory(dirPathSave);
            }
            var    bmp       = model.MainImage.FromBase64StringToImage();
            var    imageName = model.UniqueName;
            string fileSave  = Path.Combine(dirPathSave, $"{imageName}");

            var bmpOrigin = new System.Drawing.Bitmap(bmp);

            string[] imageNames = { $"50_" + imageName + ".jpg",
                                    $"100_" + imageName + ".jpg",
                                    $"300_" + imageName + ".jpg",
                                    $"600_" + imageName + ".jpg",
                                    $"1280_" + imageName + ".jpg" };

            Bitmap[] imageSave = { ImageWorker.CreateImage(bmpOrigin,   50,  50),
                                   ImageWorker.CreateImage(bmpOrigin,  100, 100),
                                   ImageWorker.CreateImage(bmpOrigin,  300, 300),
                                   ImageWorker.CreateImage(bmpOrigin,  600, 600),
                                   ImageWorker.CreateImage(bmpOrigin, 1280, 1280) };

            for (int i = 0; i < imageNames.Count(); i++)
            {
                var imageSaveEnd = System.IO.Path.Combine(dirPathSave, imageNames[i]);
                imageSave[i].Save(imageSaveEnd, System.Drawing.Imaging.ImageFormat.Jpeg);
            }

            dirPathSave = Path.Combine(dirName, model.UniqueName, "Photo");
            if (!Directory.Exists(dirPathSave))
            {
                Directory.CreateDirectory(dirPathSave);
            }
            for (int i = 0; i < model.AdditionalImage.Count; i++)
            {
                bmp      = model.AdditionalImage[i].FromBase64StringToImage();
                fileSave = Path.Combine(dirPathSave);

                bmpOrigin = new System.Drawing.Bitmap(bmp);
                string[] imageNamess = { $"50_{i+1}_" + imageName + ".jpg",
                                         $"100_{i+1}_" + imageName + ".jpg",
                                         $"300_{i+1}_" + imageName + ".jpg",
                                         $"600_{i+1}_" + imageName + ".jpg",
                                         $"1280_{i+1}_" + imageName + ".jpg" };

                Bitmap[] imageSaves = { ImageWorker.CreateImage(bmpOrigin,   50,  50),
                                        ImageWorker.CreateImage(bmpOrigin,  100, 100),
                                        ImageWorker.CreateImage(bmpOrigin,  300, 300),
                                        ImageWorker.CreateImage(bmpOrigin,  600, 600),
                                        ImageWorker.CreateImage(bmpOrigin, 1280, 1280) };

                for (int j = 0; j < imageNamess.Count(); j++)
                {
                    var imageSaveEnd = System.IO.Path.Combine(dirPathSave, imageNamess[j]);
                    imageSaves[j].Save(imageSaveEnd, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
            var cars = _context.Cars.SingleOrDefault(p => p.UniqueName == model.UniqueName);

            if (cars == null)
            {
                Car car = new Car
                {
                    UniqueName = model.UniqueName,
                    Count      = model.Count,
                    Date       = model.Date,
                    Name       = model.Name,
                    Price      = model.Price
                };
                _context.Cars.Add(car);
                _context.SaveChanges();
                return(Ok(car.Id));
            }
            return(BadRequest(new { name = "Даний автомобіль вже добалений" }));
        }
Beispiel #27
0
        public IActionResult Update([FromBody] CarUpdateVM model)
        {
            if (!ModelState.IsValid)
            {
                var errors = CustomValidator.GetErrorsByModel(ModelState);
                return(BadRequest(errors));
            }
            if (model.MainImage != null)
            {
                string dirName     = "images";
                string dirPathSave = Path.Combine(dirName, model.UniqueName);
                if (!Directory.Exists(dirPathSave))
                {
                    Directory.CreateDirectory(dirPathSave);
                }
                else
                {
                    Directory.Delete(dirPathSave, true);
                    Directory.CreateDirectory(dirPathSave);
                    System.GC.Collect();
                    System.GC.WaitForPendingFinalizers();
                }
                var    bmp       = model.MainImage.FromBase64StringToImage();
                var    imageName = model.UniqueName;
                string fileSave  = Path.Combine(dirPathSave, $"{imageName}");

                var      bmpOrigin  = new System.Drawing.Bitmap(bmp);
                string[] imageNames = { $"50_" + imageName + ".jpg",
                                        $"100_" + imageName + ".jpg",
                                        $"300_" + imageName + ".jpg",
                                        $"600_" + imageName + ".jpg",
                                        $"1280_" + imageName + ".jpg" };

                Bitmap[] imageSave = { ImageWorker.CreateImage(bmpOrigin,   50,  50),
                                       ImageWorker.CreateImage(bmpOrigin,  100, 100),
                                       ImageWorker.CreateImage(bmpOrigin,  300, 300),
                                       ImageWorker.CreateImage(bmpOrigin,  600, 600),
                                       ImageWorker.CreateImage(bmpOrigin, 1280, 1280) };

                for (int i = 0; i < imageNames.Count(); i++)
                {
                    var imageSaveEnd = System.IO.Path.Combine(dirPathSave, imageNames[i]);
                    imageSave[i].Save(imageSaveEnd, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                if (model.AdditionalImage != null)
                {
                    dirPathSave = Path.Combine(dirName, model.UniqueName, "Photo");
                    if (!Directory.Exists(dirPathSave))
                    {
                        Directory.CreateDirectory(dirPathSave);
                    }
                    for (int i = 0; i < model.AdditionalImage.Count; i++)
                    {
                        bmp      = model.AdditionalImage[i].FromBase64StringToImage();
                        fileSave = Path.Combine(dirPathSave);

                        bmpOrigin = new System.Drawing.Bitmap(bmp);
                        string[] imageNamess = { $"50_{i+1}_" + imageName + ".jpg",
                                                 $"100_{i+1}_" + imageName + ".jpg",
                                                 $"300_{i+1}_" + imageName + ".jpg",
                                                 $"600_{i+1}_" + imageName + ".jpg",
                                                 $"1280_{i+1}_" + imageName + ".jpg" };

                        Bitmap[] imageSaves = { ImageWorker.CreateImage(bmpOrigin,   50,  50),
                                                ImageWorker.CreateImage(bmpOrigin,  100, 100),
                                                ImageWorker.CreateImage(bmpOrigin,  300, 300),
                                                ImageWorker.CreateImage(bmpOrigin,  600, 600),
                                                ImageWorker.CreateImage(bmpOrigin, 1280, 1280) };

                        for (int j = 0; j < imageNamess.Count(); j++)
                        {
                            var imageSaveEnd = System.IO.Path.Combine(dirPathSave, imageNamess[j]);
                            imageSaves[j].Save(imageSaveEnd, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                    }
                }
            }
            var car = _context.Cars.SingleOrDefault(p => p.Id == model.Id);

            if (car != null)
            {
                car.Price = model.Price;
                car.Date  = model.Date;
                if (model.Name != "")
                {
                    car.Name = model.Name;
                }
                car.Count      = model.Count;
                car.UniqueName = model.UniqueName;

                _context.SaveChanges();
                return(Ok(car.Id));
            }
            return(BadRequest());
        }
Beispiel #28
0
        public ActionResult Create(OfferViewModel model)
        {
            model.IsVerified = false;
            if (ModelState.IsValid)
            {
                string link     = string.Empty;
                string filename = Guid.NewGuid().ToString() + ".jpg";
                string image    = Server.MapPath(Constants.OfferImagePath) +
                                  filename;
                if (model.SomeFile != null)
                {
                    using (Bitmap bmp = new Bitmap(model.SomeFile.InputStream))
                    {
                        var saveImage = ImageWorker.CreateImage(bmp, 450, 450);
                        if (saveImage != null)
                        {
                            saveImage.Save(image, ImageFormat.Jpeg);
                            link = Url.Content(Constants.OfferImagePath) +
                                   filename;
                        }
                    }
                }
                else
                {
                    link     = Url.Content(Constants.OfferImagePath) + "418099f8-036d-4dc2-be9a-3eef1c54088b.jpg";
                    filename = "418099f8-036d-4dc2-be9a-3eef1c54088b.jpg";
                }


                _context.offers.Add(new Entity.OfferModel
                {
                    Description  = model.Description,
                    Email        = model.Email,
                    Price        = model.Price,
                    Title        = model.Title,
                    UserID       = User.Identity.GetUserId(),
                    UserPhone    = model.UserPhone,
                    categoryId   = model.categoryId,
                    CategoryName = Find_category(model.categoryId),
                    ImageName    = filename,
                    cityId       = model.cityId,
                    cityName     = Find_city(model.cityId),
                });
                _context.SaveChanges();
                return(RedirectToAction("Index", "Multi", new { id = User.Identity.GetUserId(), area = "" }));
            }
            else
            {
                List <CategoryModel>  categories = _context.categories.ToList();
                List <CityModel>      cities     = _context.cities.ToList();
                List <SelectListItem> listItems  = new List <SelectListItem>();
                List <SelectListItem> listItems2 = new List <SelectListItem>();
                foreach (CategoryModel i in categories)
                {
                    listItems.Add(new SelectListItem
                    {
                        Value = i.Id.ToString(),
                        Text  = i.Category_name,
                    });
                }
                foreach (CityModel i in cities)
                {
                    listItems2.Add(new SelectListItem
                    {
                        Value = i.Id.ToString(),
                        Text  = i.City_name,
                    });
                }
                model.Categories = listItems;
                model.Cities     = listItems2;
                return(View(model));
            }
        }
        public ResultDto UploadImage([FromRoute] string id, [FromForm(Name = "file")] IFormFile uploadedImage)
        {
            string fileName = Guid.NewGuid().ToString() + ".jpg";
            string path     = _appEnvironment.WebRootPath + @"\Images";

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

            path = path + @"\" + fileName;
            if (uploadedImage == null)
            {
                return new ResultDto
                       {
                           IsSuccessful = false,
                           Message      = "Error"
                       }
            }
            ;
            if (uploadedImage.Length == 0)
            {
                return new ResultDto
                       {
                           IsSuccessful = false,
                           Message      = "Empty"
                       }
            }
            ;
            try
            {
                using (Bitmap bmp = new Bitmap(uploadedImage.OpenReadStream()))
                {
                    var saveImage = ImageWorker.CreateImage(bmp, 200, 125);
                    if (saveImage != null)
                    {
                        saveImage.Save(path, ImageFormat.Jpeg);
                        var user = _context.UserAdditionalInfo.Find(id);

                        if (user.Image != null && user.Image != "default.jpg")
                        {
                            System.IO.File.Delete(_appEnvironment.WebRootPath + @"\Image\" + user.Image);
                        }

                        _context.UserAdditionalInfo.Find(id).Image = fileName;
                        _context.SaveChanges();
                    }
                }
                return(new ResultDto
                {
                    IsSuccessful = true,
                    Message = "Ok"
                });
            }
            catch (Exception ex)
            {
                return(new ResultDto
                {
                    IsSuccessful = false,
                    Message = ex.Message
                });
            }
        }
    }
}