Example #1
0
        public async Task <FileManagerServiceResult> SaveImage(IFileManagerServiceInput input)
        {
            try
            {
                var filePath     = string.IsNullOrEmpty(input.FilePath) ? SaveFileInTempFolder(input.File, input.CreateUniqueName) : input.FilePath;
                var uploadParams = new ImageUploadParams()
                {
                    File           = new FileDescription(filePath),
                    Folder         = string.IsNullOrEmpty(input.SpecialFolder) ? null : input.SpecialFolder,
                    Transformation = Transformations.TransFormationsConfig.GetTransformationConfiguration(input)
                };
                await Task.FromResult(0);

                var result = _instance.Upload(uploadParams);
                return(new CloudinaryImageUploadResult()
                {
                    SecureUrl = result.SecureUri.AbsoluteUri,
                    Url = result.Uri.AbsoluteUri,
                    PublicId = result.PublicId,
                    CdnUrl = result.Uri.AbsoluteUri,
                    FileName = result.PublicId,
                    ImageSaved = true,
                    ImageSavedInCdn = true
                });
            }
            catch (Exception)
            {
                return(new CloudinaryImageUploadResult()
                {
                    ImageSaved = false
                });
            }
        }
Example #2
0
        private void SearchLogoInCloud(string ticker, ref string logoLink)
        {
            var cloudinaryAccount = new CloudinaryDotNet.Account(
                _appSettings.CloudinaryCloudName,
                _appSettings.CloudinaryApiKey,
                _appSettings.CloudinaryApiSecret);
            var cloudinary       = new CloudinaryDotNet.Cloudinary(cloudinaryAccount);
            var checkLogoInCloud = cloudinary.GetResource(ticker);

            if (checkLogoInCloud.StatusCode == HttpStatusCode.OK)
            {
                logoLink = checkLogoInCloud.SecureUrl;
            }
            else
            {
                // если лого в облаке нет, попытаемся загрузить его туда
                try
                {
                    var uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams()
                    {
                        File     = new CloudinaryDotNet.FileDescription(ticker + ".png", logoLink),
                        PublicId = ticker
                    };
                    var uploadResult = cloudinary.Upload(uploadParams);
                    if (uploadResult.StatusCode == HttpStatusCode.OK)
                    {
                        logoLink = uploadResult.SecureUrl?.ToString();
                    }
                }
                catch
                {
                    // если не получилось, оставляем logoLink как есть, т.е. ссылкой, полученной из StocksWebScraping.GetLogo
                }
            }
        }
        public async Task <IActionResult> Post([FromForm] ShopDTOin shop)
        {
            var stream = shop.Picture.OpenReadStream();

            CloudinaryDotNet.Account account = new CloudinaryDotNet.Account("drtn3myw4", "662324151252959", "nX0XPARZfpO_WRuESu_3cPoidrA");

            CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);

            CloudinaryDotNet.Actions.ImageUploadParams uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams()
            {
                File = new CloudinaryDotNet.FileDescription(shop.Picture.Name, stream)
            };

            CloudinaryDotNet.Actions.ImageUploadResult uploadResult = cloudinary.Upload(uploadParams);

            Shop newShop = new Shop();

            newShop.Name        = shop.Name;
            newShop.Address     = shop.Address;
            newShop.PicturePath = uploadResult.SecureUri.ToString();
            newShop.Locality    = shop.Locality;
            newShop.Description = shop.Description;
            _context.Shop.Add(newShop);
            await _context.SaveChangesAsync();

            return(Created($"api/Shop/{newShop.ShopId}", newShop));
        }
Example #4
0
        public JsonResult CreatePost(Post model)
        {
            if (ModelState.IsValid)
            {
                using (KonanDBContext _dc = new KonanDBContext())
                {
                    model.Id   = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 22).Replace("/", "_").Replace("+", "-");
                    model.Id_A = Session["Id"].ToString();
                    model.Date = DateTime.Now;

                    var acc = _dc.Accounts.Where(a => a.Id == model.Id_A).FirstOrDefault();
                    acc.Points += 5;

                    _dc.Entry(acc).State = EntityState.Modified;
                    _dc.SaveChanges();

                    if (model.Description != null)
                    {
                        Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);

                        MatchCollection mactches = regx.Matches(model.Description);

                        foreach (Match match in mactches)
                        {
                            model.Description = model.Description.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>");
                        }
                    }


                    if (model.File != null)
                    {
                        if (model.File.ContentLength > 0)
                        {
                            CloudinaryDotNet.Account account = new CloudinaryDotNet.Account(
                                "ursaciuc-adrian",
                                "473916817971436",
                                "S_S0CSKbWFMVh9-Se8ZXKxWLQLg");

                            CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);

                            var uploadParams = new ImageUploadParams()
                            {
                                File = new FileDescription(model.File.FileName, model.File.InputStream)
                            };
                            var uploadResult = cloudinary.Upload(uploadParams);

                            model.ImageUrl = uploadResult.Uri.OriginalString;
                        }
                    }
                    _dc.Posts.Add(model);
                    _dc.SaveChanges();
                }
            }
            return(Json("success"));
        }
        public async Task <ActionResult> Update(PersonalInfoViewModel model)
        {
            var _userService = this.Service <IUserService>();
            var userId       = User.Identity.GetUserId();

            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByIdAsync(userId);

                user.FullName    = model.Fullname;
                user.PhoneNumber = model.PhoneNumber;
                var result = await UserManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    var userEntity = await _userService.GetAsync(userId);

                    userEntity.PhoneNumber = model.PhoneNumber;
                    userEntity.FullName    = model.Fullname;

                    // Upload images to cloudinary

                    if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
                    {
                        var file       = Request.Files[0];
                        var cloudinary = new CloudinaryDotNet.Cloudinary(Models.Constants.CLOUDINARY_ACC);
                        try
                        {
                            var uploadResult = cloudinary.Upload(new ImageUploadParams()
                            {
                                File = new FileDescription(file.FileName, file.InputStream)
                            });

                            userEntity.AvatarURL = uploadResult.Uri.ToString();

                            user.AvatarURL = userEntity.AvatarURL;
                            await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);
                        }
                        catch (Exception ex)
                        {
                            return(RedirectToAction("Index", new { isSuccess = false, statusMessage = "Thay đổi thất bại. Xin vui lòng thử lại sau." }));
                        }
                    }

                    _userService.Update(userEntity);

                    return(RedirectToAction("Index", new { isSuccess = true, statusMessage = "Thay đổi thành công." }));
                }
            }


            return(RedirectToAction("Index", new { isSuccess = false, statusMessage = "Thay đổi thất bại. Xin vui lòng thử lại sau." }));
        }
Example #6
0
        public ActionResult SavePictureAPI(int vehicleID)
        {
            string userID = User.Identity.GetUserId();

            var vehicleService = this.Service <IVehicleService>();
            var vehicle        = vehicleService.Get(v => v.ID == vehicleID && v.Garage.OwnerID == userID).FirstOrDefault();

            if (vehicle == null)
            {
                return(new HttpStatusCodeResult(400, "Not found."));
            }

            if (vehicle.VehicleImages.Count > 9)
            {
                return(new HttpStatusCodeResult(400, "Không thể lưu trữ hơn 10 ảnh."));
            }

            // Upload images to cloudinary
            var cloudinary = new CloudinaryDotNet.Cloudinary(Constants.CLOUDINARY_ACC);

            try
            {
                var file         = Request.Files[0];
                var uploadResult = cloudinary.Upload(new ImageUploadParams()
                {
                    File = new FileDescription(file.FileName, file.InputStream)
                });

                // Get the image's id and url
                vehicle.VehicleImages.Add(new VehicleImage()
                {
                    ID = uploadResult.PublicId, URL = uploadResult.Uri.ToString()
                });

                vehicleService.Update(vehicle);

                return(Json(new { Id = uploadResult.PublicId, Url = uploadResult.Uri.ToString() }));
            }
            catch (Exception ex)
            {
                Response.StatusCode = 500;
                return(Json("Upload ảnh thất bại. Vui lòng thử lại sau."));
            }
        }
Example #7
0
        public async Task <ActionResult> CreateVehicleAPI(CreateVehicleModel newVehicle)
        {
            var modelService = this.Service <IModelService>();
            var userId       = this.User.Identity.GetUserId();
            var currentUser  = this.Service <IUserService>().Get(userId);

            var errorMessage = ValidateVehicleCreating(newVehicle, currentUser, modelService);

            if (errorMessage != null)
            {
                Response.StatusCode = 400;
                return(Json(new { message = errorMessage }));
            }

            var newVehicleEntity = this.Mapper.Map <Vehicle>(newVehicle);

            if (Request.Files.Count < 4 || Request.Files.Count > 10)
            {
                Response.StatusCode = 400;
                return(Json(new { message = "Chỉ được phép upload từ 4 đến 10 hình." }));
            }

            // Upload images to cloudinary
            var cloudinary = new CloudinaryDotNet.Cloudinary(Models.Constants.CLOUDINARY_ACC);
            var imageList  = new List <VehicleImage>();

            try
            {
                foreach (string fileName in Request.Files)
                {
                    var file = Request.Files[fileName];
                    if (file?.ContentLength <= 0)
                    {
                        continue;
                    }

                    // Upload to cloud
                    var uploadResult = cloudinary.Upload(new ImageUploadParams()
                    {
                        File = new FileDescription(file.FileName, file.InputStream)
                    });

                    // Get the image's id and url
                    imageList.Add(new VehicleImage()
                    {
                        ID = uploadResult.PublicId, URL = uploadResult.Uri.ToString()
                    });
                }
            }
            catch (Exception ex)
            {
                Response.StatusCode = 500;
                return(Json(new { message = "Upload ảnh thất bại. Vui lòng thử lại sau." }));
            }

            var vehicleService = this.Service <IVehicleService>();
            await vehicleService.CreateAsync(newVehicleEntity);

            foreach (var image in imageList)
            {
                image.VehicleID = newVehicleEntity.ID;
                image.Vehicle   = newVehicleEntity;
            }

            newVehicleEntity.VehicleImages = imageList;
            await vehicleService.UpdateAsync(newVehicleEntity);

            Response.StatusCode = 200;
            return(Json(new { message = "Tạo xe thành công." }));
        }
Example #8
0
        public ActionResult ViewProfile(EditProfileViewModel model)
        {
            ViewBag.Id = Session["Id"].ToString();
            string id = Session["Id"].ToString();

            if (string.IsNullOrEmpty(model.OldPassword) && string.IsNullOrEmpty(model.NewPassword) &&
                string.IsNullOrEmpty(model.ConfirmNewPassword) && model.File == null)
            {
                ModelState.AddModelError("", "No changes to save!");
                return(View(model));
            }
            if (!string.IsNullOrEmpty(model.NewPassword) && string.IsNullOrEmpty(model.OldPassword))
            {
                ModelState.AddModelError("", "Please enter the old password!");
                return(View(model));
            }

            Account account = _dc.Accounts.FirstOrDefault(a => a.Id == id);

            if (!string.IsNullOrEmpty(model.OldPassword) && !string.Equals(Account.PasswordHash(model.OldPassword), account.Password))
            {
                ModelState.AddModelError("", "The old password is incorrect!");
                return(View(model));
            }
            else
            {
                if (!string.IsNullOrEmpty(model.OldPassword) && string.IsNullOrEmpty(model.NewPassword))
                {
                    ModelState.AddModelError("", "Please enter the new password!");
                    return(View(model));
                }
                else
                {
                    if (!string.Equals(model.NewPassword, model.ConfirmNewPassword))
                    {
                        ModelState.AddModelError("", "Password confirmation must match!");
                        return(View(model));
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(model.OldPassword) && string.Equals(model.NewPassword, model.OldPassword))
                        {
                            ModelState.AddModelError("", "Your new password can't be same as old password!");
                            return(View(model));
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(model.OldPassword))
                            {
                                account.Password = Account.PasswordHash(model.NewPassword);

                                _dc.Entry(account).State = EntityState.Modified;
                                _dc.SaveChanges();
                            }
                        }
                    }
                }
            }


            if (model.File != null)
            {
                if (model.File.ContentLength > 0)
                {
                    CloudinaryDotNet.Account cloud = new CloudinaryDotNet.Account(
                        "ursaciuc-adrian",
                        "473916817971436",
                        "S_S0CSKbWFMVh9-Se8ZXKxWLQLg");

                    CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(cloud);

                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(model.File.FileName, model.File.InputStream)
                    };
                    var uploadResult = cloudinary.Upload(uploadParams);

                    model.ImageUrl = uploadResult.Uri.ToString();

                    string sessionId = Session["Id"].ToString();
                    var    acc       = _dc.Accounts.Find(sessionId);

                    acc.ImageUrl         = model.ImageUrl;
                    _dc.Entry(acc).State = EntityState.Modified;
                    _dc.SaveChanges();
                }
            }

            return(View(model));
        }
Example #9
0
 private string Upload2Cloudinary(HttpPostedFileBase file, string filename)
 {
     var settings = ConfigurationManager.AppSettings;
     CloudinaryDotNet.Account cloudinaryAccount = new CloudinaryDotNet.Account(settings["Cloudinary.CloudName"],
                                                                               settings["Cloudinary.ApiKey"],
                                                                               settings["Cloudinary.ApiSecret"]);
     string PublicId = Path.GetFileNameWithoutExtension(filename);
     CloudinaryDotNet.Actions.ImageUploadParams uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams()
     {
         //File = new CloudinaryDotNet.Actions.FileDescription(@"E:\godestalbin - Pictures\circle_blue.png"),
         File = new CloudinaryDotNet.Actions.FileDescription(filename, file.InputStream),
         PublicId = PublicId
     };
     CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(cloudinaryAccount);
     cloudinary.DeleteResources(new string[] { PublicId });
     CloudinaryDotNet.Actions.ImageUploadResult uploadResult = cloudinary.Upload(uploadParams);
     return uploadResult.Version;
 }
Example #10
0
        private string Upload2Cloudinary(Stream file, string filename)
        {
            var settings = ConfigurationManager.AppSettings;
            CloudinaryDotNet.Account cloudinaryAccount = new CloudinaryDotNet.Account(settings["Cloudinary.CloudName"],
                                                                                      settings["Cloudinary.ApiKey"],
                                                                                      settings["Cloudinary.ApiSecret"]);
            string PublicId = Path.GetFileNameWithoutExtension(filename);

            CloudinaryDotNet.Transformation et = new CloudinaryDotNet.Transformation().Angle(new string[] { "exif" }).Width(100).Height(100).Crop("thumb").Gravity("face").Radius(8);
            CloudinaryDotNet.Transformation et2 = new CloudinaryDotNet.Transformation().Effect("grayscale");
            CloudinaryDotNet.Actions.ImageUploadParams uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams()
            {
                File = new CloudinaryDotNet.Actions.FileDescription(filename, file),
                PublicId = PublicId,
                //Format = "png", //That makes the file much bigger 3,5Kb -> 55Kb
                //EagerTransforms = new List<CloudinaryDotNet.Transformation>{ et },
                Transformation =  et
                //Exif = true //Rotate automatically according to EXIF data
            };
            CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(cloudinaryAccount);
            cloudinary.DeleteResources(new string[] { PublicId });
            CloudinaryDotNet.Actions.ImageUploadResult uploadResult = cloudinary.Upload(uploadParams);
            return uploadResult.Version;
        }