Esempio n. 1
1
        public string UploadPhoto(Stream stream)
        {
            Account account = new Account(
             CLOUD_NAME,
              API_KEY,
             API_SECRET);

            Cloudinary cloudinary = new Cloudinary(account);
            var uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams()
            {
                File = new CloudinaryDotNet.Actions.FileDescription(Guid.NewGuid().ToString(), stream),
            };

            ImageUploadResult uploadResult = cloudinary.Upload(uploadParams);
            return cloudinary.Api.UrlImgUp.BuildUrl(String.Format("{0}.{1}", uploadResult.PublicId, uploadResult.Format));
        }
Esempio n. 2
0
        public void _Returns_View_WithModel(
            string cloud, string apiKey, string apiSecret, int postId)
        {
            //Arrange
            var model = new AddPostViewModel();

            var mockedAuthProvider = new Mock <IAuthenticationProvider>();
            var mockedPostService  = new Mock <IPostService>();

            var mockedViewModelFactory = new Mock <IViewModelFactory>();

            mockedViewModelFactory.Setup(v => v.CreateAddPostViewModel(It.IsAny <Cloudinary>())).Returns(model);

            var mockedAcc        = new CloudinaryDotNet.Account(cloud, apiKey, apiSecret);
            var mockedCloudinary = new Mock <Cloudinary>(mockedAcc);

            var postController = new PostController(mockedAuthProvider.Object, mockedPostService.Object,
                                                    mockedViewModelFactory.Object, mockedCloudinary.Object);

            //Act
            var res = postController.Details(postId) as ViewResult;

            //Assert
            mockedPostService.Verify(s => s.GetPostById(postId), Times.Once);
        }
Esempio n. 3
0
        public async Task <IActionResult> peopleDetail(PeopleDetail model)
        {
            var user = await GetCurrentUserAsync();

            if (user != null)
            {
                var role = await _userManager.GetRolesAsync(user);

                TempData["userRole"] = role[0];
                string rid       = HttpContext.Request.Form["restId"];
                string sortOrder = HttpContext.Request.Form["sortOrder"];
                string firstName = HttpContext.Request.Form["fname"];
                string lastname  = HttpContext.Request.Form["lname"];

                string filepath = HttpContext.Request.Form["filePath"];

                if (!string.IsNullOrEmpty(filepath))
                {
                    CloudinaryDotNet.Account account = new CloudinaryDotNet.Account("hkm2gz727", "654416183426452", "AZJIv_WvBo1Z7gkzN-uXFVg2_BE");
                    Cloudinary cloudinary            = new Cloudinary(account);

                    CloudinaryDotNet.Actions.ImageUploadParams uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams();
                    uploadParams.File = new CloudinaryDotNet.Actions.FileDescription(filepath);

                    CloudinaryDotNet.Actions.ImageUploadResult uploadResult = await cloudinary.UploadAsync(uploadParams);

                    string url = cloudinary.Api.UrlImgUp.BuildUrl(String.Format("{0}.{1}", uploadResult.PublicId, uploadResult.Format));
                    model.imageUrl = url;
                }
                else
                {
                    string imageurl = HttpContext.Request.Form["imageurl"];
                    model.imageUrl = imageurl;
                }
                model.userId       = user.Id;
                model.firstName    = firstName;
                model.lastName     = lastname;
                model.restaurantId = Convert.ToInt32(rid);
                model.createdDate  = DateTime.Now;
                model.modifiedDate = DateTime.Now;
                if (model.id != 0)
                {
                    _context.PeopleDetail.Update(model);
                    _context.SaveChanges();
                }
                else
                {
                    model.sortOrder = _context.PeopleDetail.Where(a => a.restaurantId == Convert.ToInt32(rid)).Max(a => a.sortOrder) + 1;
                    _context.PeopleDetail.Add(model);
                    _context.SaveChanges();
                }


                return(Redirect("~/Admin/people?resturant=" + model.restaurantId));
            }
            else
            {
                return(RedirectToAction("QuickRegister", "Account"));
            }
        }
Esempio n. 4
0
        public async Task <IActionResult> MenuItemDetails(MenuItemDetail model)
        {
            string restaurantId   = HttpContext.Request.Form["restId"];
            string menuCategoryId = HttpContext.Request.Form["menuCategoryId"];
            var    user           = await GetCurrentUserAsync();

            if (user != null)
            {
                var role = await _userManager.GetRolesAsync(user);

                TempData["userRole"] = role[0];
                string filepath = HttpContext.Request.Form["filePath"];
                if (!string.IsNullOrEmpty(filepath))
                {
                    CloudinaryDotNet.Account account = new CloudinaryDotNet.Account("hkm2gz727", "654416183426452", "AZJIv_WvBo1Z7gkzN-uXFVg2_BE");
                    Cloudinary cloudinary            = new Cloudinary(account);

                    CloudinaryDotNet.Actions.ImageUploadParams uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams();
                    uploadParams.File = new CloudinaryDotNet.Actions.FileDescription(filepath);

                    CloudinaryDotNet.Actions.ImageUploadResult uploadResult = await cloudinary.UploadAsync(uploadParams);

                    string url = cloudinary.Api.UrlImgUp.BuildUrl(String.Format("{0}.{1}", uploadResult.PublicId, uploadResult.Format));
                    model.menuItemImageUrl = url;
                }
                else
                {
                    string imageurl = HttpContext.Request.Form["imageurl"];
                    model.menuItemImageUrl = imageurl;
                }

                model.menuCategoryId = Convert.ToInt32(menuCategoryId);
                model.restaurantId   = Convert.ToInt32(restaurantId);

                // if (ModelState.IsValid)
                // {
                if (model.menuItemId != 0)
                {
                    model.createdDate = DateTime.Now;
                    _context.MenuItemDetail.Update(model);
                    _context.SaveChanges();
                }
                else
                {
                    model.createdDate = DateTime.Now;

                    model.sortOrder = _context.MenuItemDetail.Where(a => a.restaurantId == Convert.ToInt32(restaurantId) && a.menuCategoryId == Convert.ToInt32(menuCategoryId)).Max(a => a.sortOrder) + 1;
                    _context.MenuItemDetail.Add(model);
                    _context.SaveChanges();
                }

                // }
                return(Redirect("~/Admin/MenuItems" + "?resturant=" + model.restaurantId + "&itemtype=" + model.menuCategoryId));
                //return RedirectToAction("MenuItems", "Admin");
            }
            else
            {
                return(RedirectToAction("QuickRegister", "Account"));
            }
        }
Esempio n. 5
0
        public void _Return_View_With_Model(string cloud, string apiKey, string apiSecret, int newsId)
        {
            //Arrange
            var model = new NewsDetailsViewModel();
            var news  = new Models.News();

            var mockedAuthProvider = new Mock <IAuthenticationProvider>();

            var mockedNewsService = new Mock <INewsService>();

            mockedNewsService.Setup(n => n.GetNewsById(newsId)).Returns(news);

            var mockedViewModelFactory = new Mock <IViewModelFactory>();

            mockedViewModelFactory.Setup(v => v.CreateNewsDetailsViewModel(It.IsAny <Models.News>())).Returns(model);

            var fakeAcc          = new CloudinaryDotNet.Account(cloud, apiKey, apiSecret);
            var mockedCloudinary = new Mock <Cloudinary>(fakeAcc);

            var newsControllerSUT = new NewsController(mockedAuthProvider.Object, mockedNewsService.Object, mockedViewModelFactory.Object, mockedCloudinary.Object);

            //Act
            var res = newsControllerSUT.Details(newsId) as ViewResult;

            //Assert
            Assert.AreEqual(model, res.Model);
        }
Esempio n. 6
0
        public void _Returns_Correct_Model(
            string cloud, string apiKey, string apiSecret, int postId)
        {
            //Arrange
            var post  = new Models.Post();
            var model = new PostDetailsViewModel();

            var mockedAuthProvider = new Mock <IAuthenticationProvider>();

            var mockedPostService = new Mock <IPostService>();

            mockedPostService.Setup(s => s.GetPostById(It.IsAny <int>())).Returns(post);

            var mockedViewModelFactory = new Mock <IViewModelFactory>();

            mockedViewModelFactory.Setup(v => v.CreatePostDetailsViewModel(It.IsAny <Models.Post>())).Returns(model);

            var mockedAcc        = new CloudinaryDotNet.Account(cloud, apiKey, apiSecret);
            var mockedCloudinary = new Mock <Cloudinary>(mockedAcc);

            var postController = new PostController(mockedAuthProvider.Object, mockedPostService.Object,
                                                    mockedViewModelFactory.Object, mockedCloudinary.Object);

            //Act
            var res = postController.Details(postId) as ViewResult;

            //Assert
            Assert.AreEqual(model, res.Model);
        }
        public void _Return_RedirectResult_WithCorrect_Url_WhenProvider_ReturnsSuccess(
            string username,
            string password,
            bool rememberMe,
            string returnUrl)
        {
            //Arrange
            var mockedProvider = new Mock <IAuthenticationProvider>();
            var mockedFactory  = new Mock <IUserFactory>();

            var fakeAcc          = new CloudinaryDotNet.Account("sdfsdfsd", "sdfsdfsdf", "sdfsdfsdf");
            var mockedCloudinary = new Mock <Cloudinary>(fakeAcc);

            var loginViewModel = new LoginViewModel()
            {
                Username   = username,
                Password   = password,
                RememberMe = rememberMe
            };

            var controller = new AccountController(mockedProvider.Object, mockedFactory.Object, mockedCloudinary.Object);

            //Act
            var result = controller.Login(loginViewModel, returnUrl) as RedirectResult;

            //Assert
            Assert.AreEqual(returnUrl, result.Url);
        }
        public async Task UploadProfilePictureCloudinary(ClaimsPrincipal user, UploadProfilePictureInputModel inputModel)
        {
            var userId            = this.userManager.GetUserId(user);
            var coudinaryUsername = configuration.GetValue <string>("Cloudinary:Username");
            var apiKey            = configuration.GetValue <string>("Cloudinary:ApiKey");
            var apiSecret         = configuration.GetValue <string>("Cloudinary:ApiSecret");

            CloudinaryDotNet.Account account =
                new CloudinaryDotNet.Account(coudinaryUsername, apiKey, apiSecret);

            Cloudinary cloudinary = new Cloudinary(account);

            var fileName = $"{userId}_Profile_Picture";

            var stream = inputModel.UploadImage.OpenReadStream();

            CloudinaryDotNet.Actions.ImageUploadParams uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams()
            {
                File     = new FileDescription(inputModel.UploadImage.FileName, stream),
                PublicId = fileName,
            };

            CloudinaryDotNet.Actions.ImageUploadResult uploadResult = await cloudinary.UploadAsync(uploadParams);

            var updatedUrl = (await cloudinary.GetResourceAsync(uploadResult.PublicId)).Url;

            await SaveImageNameToDb(user, updatedUrl);
        }
Esempio n. 9
0
        public tw_ImagesSize Upload(HttpPostedFileBase file, string publicId)
        {
            var settings = ConfigurationManager.AppSettings;

            CloudinaryDotNet.Account account =
                new CloudinaryDotNet.Account(settings["cloudinary.cloud"], settings["cloudinary.apikey"], settings["cloudinary.apisecret"]);

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

            CloudinaryDotNet.Actions.ImageUploadParams uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams()
            {
                File     = new CloudinaryDotNet.Actions.FileDescription(file.FileName, file.InputStream),
                PublicId = publicId
            };

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

            var imagesSize = new tw_ImagesSize()
            {
                thumb = new Helpers.CloudinaryAPI().cloudinary().Api.UrlImgUp.Transform(
                    new Transformation().Width(150).Crop("fill")).BuildUrl(publicId + ".jpg"),
                small = new Helpers.CloudinaryAPI().cloudinary().Api.UrlImgUp.Transform(
                    new Transformation().Width(480).Crop("fill")).BuildUrl(publicId + ".jpg"),
                medium = new Helpers.CloudinaryAPI().cloudinary().Api.UrlImgUp.Transform(
                    new Transformation().Width(760).Crop("fill")).BuildUrl(publicId + ".jpg"),
                large = new Helpers.CloudinaryAPI().cloudinary().Api.UrlImgUp.Transform(
                    new Transformation().Width(1024).Crop("fill")).BuildUrl(publicId + ".jpg"),
                face = new Helpers.CloudinaryAPI().cloudinary().Api.UrlImgUp.Transform(
                    new Transformation().Width(150).Height(150).Crop("thumb").Gravity("face")).BuildUrl(publicId + ".jpg"),
                original = new Helpers.CloudinaryAPI().cloudinary().Api.UrlImgUp.BuildUrl(publicId + ".jpg")
            };

            return(imagesSize);
        }
Esempio n. 10
0
        public void UploadProfilePictureCloudinary(ClaimsPrincipal user, UploadProfilePictureInputModel inputModel)
        {
            var userId = this.userManager.GetUserId(user);

            CloudinaryDotNet.Account account =
                new CloudinaryDotNet.Account("svetlinmld", "412472163518427", "M90sSSvXSYNzKQ3-l7qb-KGLpSY");

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

            var fileName = $"{userId}_Profile_Picture";

            var stream = inputModel.UploadImage.OpenReadStream();

            CloudinaryDotNet.Actions.ImageUploadParams uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams()
            {
                File     = new FileDescription(inputModel.UploadImage.FileName, stream),
                PublicId = fileName,
            };

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

            var updatedUrl = cloudinary.GetResource(uploadResult.PublicId).Url;

            SaveImageNameToDb(user, updatedUrl);
        }
Esempio n. 11
0
        //
        // GET: /Manage/Index
        public async Task<ActionResult> Index(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Ваш пароль изменен."
                : message == ManageMessageId.SetPasswordSuccess ? "Пароль задан."
                : message == ManageMessageId.SetTwoFactorSuccess ? "Настроен поставщик двухфакторной проверки подлинности."
                : message == ManageMessageId.Error ? "Произошла ошибка."
                : message == ManageMessageId.AddPhoneSuccess ? "Ваш номер телефона добавлен."
                : message == ManageMessageId.RemovePhoneSuccess ? "Ваш номер телефона удален."
                : "";

            var userId = User.Identity.GetUserId();
            ApplicationUser user = await UserManager.FindByEmailAsync(User.Identity.Name);
            Account account = new Account("kuzzya", "649899148786625", "Em9LZocDSzlf5Jf9ikhTRKwvuhY");
            CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);

            var model = new IndexViewModel
            {
                HasPassword = HasPassword(),
                PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
                TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
                Logins = await UserManager.GetLoginsAsync(userId),
                BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId),
                Name=user.Name,
                Hobby=user.Hobby,
                ShortDescription=user.ShortDescription,
                Surname=user.Surname
            };
            
            return View(model);
        }
        public string Cloudinary(byte[] image, string name)
        {
            //IConfigurationBuilder builder = new ConfigurationBuilder()
            //.SetBasePath(Directory.GetCurrentDirectory())
            //.AddJsonFile("ClodyinaryConfig.json", optional: true, reloadOnChange: true);

            //IConfigurationRoot configuration = builder.Build();
            //configurationSection.Key => FilePath
            // configurationSection.Value => C:\\temp\\logs\\output.txt
            //IConfigurationSection configurationSection = configuration.GetSection("AppConfig");

            ImageConverter imageConverter = new ImageConverter();
            var            config         = new ConfigurationBuilder().AddJsonFile(@"C:\Users\TELMAN\source\repos\ImageManager\ImageManager.Storage\ClodyinaryConfig.json").Build().GetChildren();
            Account        account        = new CloudinaryDotNet.Account("damiiis6r", "591262355387469", "VBgPuS6TcTySIel8VWMBJazGNag");
            Cloudinary     cloudinary     = new Cloudinary(account);
            Image          img            = imageConverter.byteArrayToImage(image);


            MemoryStream ms = new MemoryStream(image);

            ImageUploadParams uploadParams = new ImageUploadParams()
            {
                File           = new FileDescription(name, ms),
                UseFilename    = true,
                UniqueFilename = false
            };
            ImageUploadResult uploadResult = cloudinary.Upload(uploadParams);

            return(uploadResult.SecureUri.ToString());
        }
Esempio n. 13
0
        public void _Return_ViewWithModel_WhenProvider_ReturnsFail(
            string username,
            string password,
            bool rememberMe,
            string returnUrl)
        {
            //Arrange
            var mockedProvider = new Mock <IAuthenticationProvider>();

            mockedProvider.Setup(
                p =>
                p.SignInWithPassword(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(),
                                     It.IsAny <bool>()))
            .Returns(SignInStatus.Failure);

            var mockedFactory = new Mock <IUserFactory>();

            var fakeAcc          = new CloudinaryDotNet.Account("sdfsdfsd", "sdfsdfsdf", "sdfsdfsdf");
            var mockedCloudinary = new Mock <Cloudinary>(fakeAcc);

            var loginViewModel = new LoginViewModel()
            {
                Username   = username,
                Password   = password,
                RememberMe = rememberMe
            };

            var controller = new AccountController(mockedProvider.Object, mockedFactory.Object, mockedCloudinary.Object);

            //Act
            var res = controller.Login(loginViewModel, returnUrl) as ViewResult;

            //Assert
            Assert.AreEqual(loginViewModel, res.Model);
        }
Esempio n. 14
0
        public void _Return_ViewWithModel_If_ModelState_NotValid(
            string username,
            string password,
            bool rememberMe,
            string returnUrl)
        {
            //Arrange
            var mockedProvider = new Mock <IAuthenticationProvider>();
            var mockedFactory  = new Mock <IUserFactory>();

            var fakeAcc          = new CloudinaryDotNet.Account("sdfsdfsd", "sdfsdfsdf", "sdfsdfsdf");
            var mockedCloudinary = new Mock <Cloudinary>(fakeAcc);

            var loginViewModel = new LoginViewModel()
            {
                Username   = username,
                Password   = password,
                RememberMe = rememberMe
            };

            var controller = new AccountController(mockedProvider.Object, mockedFactory.Object, mockedCloudinary.Object);

            controller.ModelState.AddModelError("key", "error");

            //Act
            var res = controller.Login(loginViewModel, returnUrl) as ViewResult;

            //Assert
            Assert.AreSame(loginViewModel, res.Model);
        }
Esempio n. 15
0
        public void _Call_Provider_SignInWithPassword_ModelState_IsValid(
            string username,
            string password,
            bool rememberMe,
            string returnUrl)
        {
            //Arrange
            var mockedProvider = new Mock <IAuthenticationProvider>();
            var mockedFactory  = new Mock <IUserFactory>();

            var fakeAcc          = new CloudinaryDotNet.Account("sdfsdfsd", "sdfsdfsdf", "sdfsdfsdf");
            var mockedCloudinary = new Mock <Cloudinary>(fakeAcc);

            var loginViewModel = new LoginViewModel()
            {
                Username   = username,
                Password   = password,
                RememberMe = rememberMe
            };

            var controller = new AccountController(mockedProvider.Object, mockedFactory.Object, mockedCloudinary.Object);

            //Act
            controller.Login(loginViewModel, returnUrl);

            //Assert
            mockedProvider.Verify(
                p => p
                .SignInWithPassword(
                    username,
                    password,
                    rememberMe,
                    It.IsAny <bool>()),
                Times.Once);
        }
        public string CloudUpload(Models.RegisterBindingModel user)
        {
            if (HandleFileUpload(ref user))
            {
                Account acount = new Account("gigantor", "986286566519458", "GT87e1BTMnfLut1_gXhSH0giZPg");
                Cloudinary cloudinary = new Cloudinary(acount);

                string userId = this.User.Identity.GetUserId();
                ApplicationUser user1 = db.Users.Find(userId);
                if (user1.ProfilePicUrl != null && user1.ProfilePicUrl.StartsWith("http://res.cloudinary.com/gigantor/image/upload/"))  //this block of code deletes the previous image if the user had one
                {
                    //this here is just a string manipulation to get to the ImageID from cloudinary
                    string assist = "http://res.cloudinary.com/gigantor/image/upload/";
                    string part1 = user1.ProfilePicUrl.Remove(user1.ProfilePicUrl.IndexOf(assist), assist.Length);
                    string part2 = part1.Remove(0, 12);
                    string toDelete = part2.Remove(part2.Length - 4);
                    cloudinary.DeleteResources(toDelete);  //this finally deletes the image
                }

                user1.ProfilePicUrl = CloudinaryUpload(user);
                db.Entry(user1).State = EntityState.Modified;
                db.SaveChanges();
                return user1.ProfilePicUrl;
            }
            return user.ProfileUrl;
        }
Esempio n. 17
0
        public void UploadProfilePicture(IFormFile image, string username)
        {
            var user = this.dbService.DbContext.Users.FirstOrDefault(u => u.UserName == username);

            CloudinaryDotNet.Account cloudAccount = new CloudinaryDotNet.Account(this.cloudConfig.Value.CloudName, this.cloudConfig.Value.ApiKey, this.cloudConfig.Value.ApiSecret);

            Cloudinary cloudinary = new Cloudinary(cloudAccount);

            var stream = image.OpenReadStream();

            CloudinaryDotNet.Actions.ImageUploadParams uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams()
            {
                File     = new FileDescription(image.FileName, stream),
                PublicId = string.Format(ServicesConstants.CloudinaryPublicId, username)
            };

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

            string url = cloudinary.Api.UrlImgUp.BuildUrl(string.Format(ServicesConstants.CloudinaryPictureName, username));

            var updatedUrl = cloudinary.GetResource(uploadParams.PublicId).Url;

            user.ProfilePicutre = updatedUrl;

            this.dbService.DbContext.Entry(user).State = EntityState.Modified;
            this.dbService.DbContext.SaveChanges();
        }
        public string CloudUploadEdit(Course course)
        {
            if (HandleFileUpload(ref course))
            {
                var courseCurrentPicture = db.Courses.Select(x => x.PictureUrl);
                var array = courseCurrentPicture.ToArray();
                var lastElement = array[array.Length - 1];
                Account acount = new Account("gigantor", "986286566519458", "GT87e1BTMnfLut1_gXhSH0giZPg");
                Cloudinary cloudinary = new Cloudinary(acount);

                if (lastElement != null && course.PictureUrl.StartsWith("http://res.cloudinary.com/gigantor/image/upload/"))  //this block of code deletes the previous image if the user had one
                {
                    //this here is just a string manipulation to get to the ImageID from cloudinary
                    string assist = "http://res.cloudinary.com/gigantor/image/upload/";
                    string part1 = lastElement.Remove(lastElement.IndexOf(assist), assist.Length);
                    string part2 = part1.Remove(0, 12);
                    string toDelete = part2.Remove(part2.Length - 4);
                    cloudinary.DeleteResources(toDelete);  //this finally deletes the image
                }
                   
                course.PictureUrl = CloudinaryUpload(course);
            
                return course.PictureUrl;
            }

            course.PictureUrl = "http://res.cloudinary.com/gigantor/image/upload/v1441017337/wwgb50xuqulq7utflsjo.gif";
            return course.PictureUrl;
        }
Esempio n. 19
0
        static CloudinaryHelper()
        {
            var clacc = new Account(Environment.GetEnvironmentVariable("CLOUDINARY_CLOUD_NAME"),
                                    Environment.GetEnvironmentVariable("CLOUDINARY_API_KEY"),
                                    Environment.GetEnvironmentVariable("CLOUDINARY_API_SECRET"));

            Cloudinary = new Cloudinary(clacc);
        }
Esempio n. 20
0
        public PhotoService(IOptions <CloudinarySettings> config)
        {
            var cloud   = config.Value;
            var account = new CloudinaryDotNet.Account(cloud.CloudName, cloud.ApiKey, cloud.ApiSecret);

            // var acc = new CloudinaryDotNet.Account(cloud.CloudName, cloud.ApiKey, cloud.ApiSecret);
            _cloudinary = new Cloudinary(account);
        }
Esempio n. 21
0
 public static void Init()
 {
     Account account = new Account(
     "rockitshipshawty",
     "969736378743428",
     "SouveLJZlKhFpf2B01Qm80bV_9E");
     Cloudinary = new Cloudinary(account);
 }
Esempio n. 22
0
        public CloudinaryPhotoManager()
        {
            var account = new Account(
 "my_cloud_name",
 "my_api_key",
 "my_api_secret");
            _cloudinary = new Cloudinary(account);
        }
Esempio n. 23
0
        private ServiceCollection SetServices()
        {
            var services = new ServiceCollection();

            services.AddDbContext <UnravelTravelDbContext>(
                opt => opt.UseInMemoryDatabase(Guid.NewGuid().ToString()));

            services
            .AddIdentity <UnravelTravelUser, ApplicationRole>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequiredLength         = 6;
            })
            .AddEntityFrameworkStores <UnravelTravelDbContext>()
            .AddUserStore <ApplicationUserStore>()
            .AddRoleStore <ApplicationRoleStore>()
            .AddDefaultTokenProviders();

            // Data repositories
            services.AddScoped(typeof(IDeletableEntityRepository <>), typeof(EfDeletableEntityRepository <>));
            services.AddScoped(typeof(IRepository <>), typeof(EfRepository <>));

            // Application services
            services.AddTransient <IEmailSender, SendGridEmailSender>(provider =>
                                                                      new SendGridEmailSender(new LoggerFactory(), "SendGridKey", "*****@*****.**", "UnravelTravel"));

            services.AddScoped <IDestinationsService, DestinationsService>();
            services.AddScoped <ICountriesService, CountriesService>();
            services.AddScoped <IRestaurantsService, RestaurantsService>();
            services.AddScoped <IActivitiesService, ActivitiesService>();
            services.AddScoped <ITicketsService, TicketsService>();
            services.AddScoped <IReservationsService, ReservationsService>();
            services.AddScoped <IShoppingCartsService, ShoppingCartsService>();

            // Identity stores
            services.AddTransient <IUserStore <UnravelTravelUser>, ApplicationUserStore>();
            services.AddTransient <IRoleStore <ApplicationRole>, ApplicationRoleStore>();

            // AutoMapper
            AutoMapperConfig.RegisterMappings(typeof(ActivityViewModel).GetTypeInfo().Assembly);

            // Cloudinary Setup
            var cloudinaryAccount = new CloudinaryDotNet.Account(CloudinaryConfig.CloudName, CloudinaryConfig.ApiKey, CloudinaryConfig.ApiSecret);
            var cloudinary        = new Cloudinary(cloudinaryAccount);

            services.AddSingleton(cloudinary);

            var context = new DefaultHttpContext();

            services.AddSingleton <IHttpContextAccessor>(new HttpContextAccessor {
                HttpContext = context
            });

            return(services);
        }
Esempio n. 24
0
 static PhotoService()
 {
     CloudAccount = new Account
     {
         ApiKey = System.Configuration.ConfigurationManager.AppSettings["ApiKey"],
         ApiSecret = System.Configuration.ConfigurationManager.AppSettings["ApiSecret"],
         Cloud = System.Configuration.ConfigurationManager.AppSettings["Cloud"]
     };
 }
Esempio n. 25
0
        public async Task <IActionResult> New(CreateDogViewModel model)
        {
            var validImage = model.Image == null || model.Image.FileName.EndsWith(".jpg");

            if (!ModelState.IsValid || !validImage || model.BirthDate > DateTime.UtcNow)
            {
                return(View(model));
            }

            else
            {
                var user = await userManager.GetUserAsync(User);

                var dog = new Dog
                {
                    Name          = model.Name,
                    BirthDate     = model.BirthDate,
                    Province      = model.Province,
                    Breed         = model.Breed,
                    IsDisinfected = model.IsDisinfected,
                    IsVaccinated  = model.IsVaccinated,
                    OwnerNotes    = model.OwnerNotes,
                    IsCastrated   = model.IsCastrated,
                    Gender        = model.Gender,
                    Owner         = user
                };

                if (model.Image != null)
                {
                    var acc = new CloudinaryDotNet.Account("dmm9z8uow", "367813196612582", "I3kSZZCbEN-OHiyD35eh8mzyO8k");

                    var cloud = new Cloudinary(acc);

                    var file = new FileDescription(model.Image.FileName, model.Image.OpenReadStream());

                    var upload = new ImageUploadParams()
                    {
                        File = file
                    };

                    var image = await cloud.UploadAsync(upload);

                    var pic = new Pic
                    {
                        ImageUrl = image.Uri.AbsoluteUri
                    };

                    dog.Images.Add(pic);
                }

                await context.Dogs.AddAsync(dog);

                await context.SaveChangesAsync();

                return(RedirectToAction("Index", "Home"));
            }
        }
Esempio n. 26
0
        public Cloudinary cloudinary()
        {
            var settings = ConfigurationManager.AppSettings;

            CloudinaryDotNet.Account account =
                new CloudinaryDotNet.Account(settings["cloudinary.cloud"], settings["cloudinary.apikey"], settings["cloudinary.apisecret"]);

            CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);
            return(cloudinary);
        }
Esempio n. 27
0
 public PagesController(ICRUDRepo repo, IOptions <CloudinarySettings> cloudinarySettings)
 {
     CloudinaryDotNet.Account account = new CloudinaryDotNet.Account()
     {
         ApiKey    = cloudinarySettings.Value.ApiKey,
         ApiSecret = cloudinarySettings.Value.ApiSecret,
         Cloud     = cloudinarySettings.Value.CloudName
     };
     _cloudHelper = new CloudinaryHelper(account);
     _repo        = repo;
 }
Esempio n. 28
0
        public void _Throw_ArgumentNullException_IfUserFactory_IsNull()
        {
            //Arrange
            var mockedProvider = new Mock <IAuthenticationProvider>();

            var fakeAcc          = new CloudinaryDotNet.Account("sdfsdfsd", "sdfsdfsdf", "sdfsdfsdf");
            var mockedCloudinary = new Mock <Cloudinary>(fakeAcc);

            //Act & Assert
            Assert.Throws <ArgumentNullException>(() => new AccountController(mockedProvider.Object, null, mockedCloudinary.Object));
        }
Esempio n. 29
0
        public ProductDocument Create(ProductDocument productDocument, IFormFile image)
        {
            productDocument.Id          = Guid.NewGuid();
            productDocument.DateCreated = DateTime.UtcNow;
            productDocument.Owner       = _userContext.UserId.Value;

            var allowedContentTypes = new string[] { "image/jpg", "image/png", "image/jpeg" };

            try
            {
                var  file     = image;
                Guid username = _userContext.UserId.Value;
                if (!allowedContentTypes.Contains(file.ContentType))
                {
                    throw new InvalidOperationException("Invalid image extension");
                }
                //string folderName = "Upload";
                //string webRootPath = _hostingEnvironment.ContentRootPath;
                //string newPath = Path.Combine(webRootPath, folderName, "Products", $"{productDocument.Id}");
                //if (!Directory.Exists(newPath))
                //{
                //	Directory.CreateDirectory(newPath);
                //}
                if (file.Length > 0)
                {
                    CloudinaryDotNet.Account account = new CloudinaryDotNet.Account(
                        _cloudinaryMetaData.CloudName,
                        _cloudinaryMetaData.ApiKey,
                        _cloudinaryMetaData.ApiSecret);

                    Cloudinary cloudinary = new Cloudinary(account);

                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.RemoveSpecialCharacters().Trim('"');

                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(fileName, file.OpenReadStream())
                    };
                    var uploadResult = cloudinary.Upload(uploadParams);

                    //string fullPath = Path.Combine(newPath, fileName);
                    //using (var stream = new FileStream(fullPath, FileMode.Create))
                    //{
                    //	file.CopyTo(stream);
                    //}
                    productDocument.ProductPhoto = uploadResult.SecureUrl.AbsoluteUri;
                }
                return(_productRepository.Create(productDocument));
            }
            catch (System.Exception ex)
            {
                throw new Exception("Upload Failed, " + ex.Message);
            }
        }
Esempio n. 30
0
        public PhotoController(IDataRepository repo, IMapper mapper, IOptions <CloudinarySettings> cloudinarySettings) : base(repo, mapper)
        {
            this._cloudinaryConfig = cloudinarySettings;

            CloudinaryDotNet.Account acc = new CloudinaryDotNet.Account(
                _cloudinaryConfig.Value.CloudName,
                _cloudinaryConfig.Value.ApiKey,
                _cloudinaryConfig.Value.ApiSecret
                );

            _cloudinary = new Cloudinary(acc);
        }
Esempio n. 31
0
        static HomeController()
        {
            PhotoAlbumContainer album = new PhotoAlbumContainer();
            album.Database.Initialize(false);

            Account acc = new Account(
                    Properties.Settings.Default.CloudName,
                    Properties.Settings.Default.ApiKey,
                    Properties.Settings.Default.ApiSecret);

            m_cloudinary = new Cloudinary(acc);
        }
Esempio n. 32
0
        public CloudinaryManager(CloudinarySettings cloudinarySettings)
        {
            this._cloudinaryConfig = cloudinarySettings;

            CloudinaryDotNet.Account acc = new CloudinaryDotNet.Account(
                _cloudinaryConfig.CloudName,
                _cloudinaryConfig.ApiKey,
                _cloudinaryConfig.ApiSecret
                );

            _cloudinary = new Cloudinary(acc);
        }
Esempio n. 33
0
        public void _NotThrow_IfEveryting_PassedCorrectly()
        {
            //Arrange
            var mockedProvider = new Mock <IAuthenticationProvider>();
            var mockedFactory  = new Mock <IUserFactory>();

            var fakeAcc          = new CloudinaryDotNet.Account("sdfsdfsd", "sdfsdfsdf", "sdfsdfsdf");
            var mockedCloudinary = new Mock <Cloudinary>(fakeAcc);

            //Act & Assert
            Assert.DoesNotThrow(() => new AccountController(mockedProvider.Object, mockedFactory.Object, mockedCloudinary.Object));
        }
Esempio n. 34
0
        public void _ShouldThrow_ArgumentNullException_NewsService_IsNull()
        {
            //Arrange
            var mockedAuthProvider     = new Mock <IAuthenticationProvider>();
            var mockedViewModelFactory = new Mock <IViewModelFactory>();

            var fakeAcc          = new CloudinaryDotNet.Account("fake", "fake", "fake");
            var mockedCloudinary = new Mock <Cloudinary>(fakeAcc);

            //Act & Assert
            Assert.Throws <ArgumentNullException>(() => new NewsController(mockedAuthProvider.Object, null, mockedViewModelFactory.Object, mockedCloudinary.Object));
        }
Esempio n. 35
0
        private ServiceCollection SetServices()
        {
            var services = new ServiceCollection();

            services.AddDbContext <ApplicationDbContext>(
                opt => opt.UseInMemoryDatabase(Guid.NewGuid().ToString()));

            services
            .AddIdentity <ApplicationUser, ApplicationRole>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequiredLength         = 5;
                options.SignIn.RequireConfirmedAccount  = true;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            // Data repositories
            services.AddScoped(typeof(IDeletableEntityRepository <>), typeof(EfDeletableEntityRepository <>));
            services.AddScoped(typeof(IRepository <>), typeof(EfRepository <>));

            var cloudinaryAccount = new CloudinaryDotNet.Account("dv3tfjvk0", "834565789315234", "fh3CxN8m5yoWHhCuxfl6xQJ50hQ");
            var cloudinary        = new Cloudinary(cloudinaryAccount);

            services.AddSingleton(cloudinary);

            // Application services
            services.AddTransient <GeodesyApi.Services.Messaging.IEmailSender, SendGridEmailSender>(provider =>
                                                                                                    new SendGridEmailSender(/*this.Configuration["SendGridApiKey"]*/));
            services.AddTransient <GeodesyApi.Services.Messaging.IEmailSender>(x => new SendGridEmailSender(/*this.Configuration["SendGridApiKey"]*/));
            services.AddTransient <ISettingsService, SettingsService>();
            services.AddTransient <IMaterialsService, MaterialsService>();
            services.AddTransient <INewsService, NewsService>();
            services.AddTransient <ICommentsService, CommentsService>();
            services.AddTransient <ICloudinaryService, CloudinaryService>(c => new CloudinaryService(cloudinary));
            services.AddTransient <IProjectsService, ProjectsService>();
            services.AddTransient <IContactsService, ContactsService>();


            // Cloudinary Setup


            var context = new DefaultHttpContext();

            services.AddSingleton <IHttpContextAccessor>(new HttpContextAccessor {
                HttpContext = context
            });

            return(services);
        }
Esempio n. 36
0
        public void DeleteImage(List <string> publicId)
        {
            var settings = ConfigurationManager.AppSettings;

            CloudinaryDotNet.Account account =
                new CloudinaryDotNet.Account(settings["cloudinary.cloud"], settings["cloudinary.apikey"], settings["cloudinary.apisecret"]);

            CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);
            foreach (var item in publicId)
            {
                cloudinary.DeleteResources(item);
            }
        }
Esempio n. 37
0
        public void _Throws_ArgumentNullException_When_AuthProvider_IsNull(string cloud, string apiKey, string apiSecret)
        {
            //Arrange
            var mockedPostService      = new Mock <IPostService>();
            var mockedViewModelFactory = new Mock <IViewModelFactory>();

            var mockedAcc        = new CloudinaryDotNet.Account(cloud, apiKey, apiSecret);
            var mockedCloudinary = new Mock <Cloudinary>(mockedAcc);

            //Act and Assert
            Assert.Throws <ArgumentNullException>(() => new PostController(null, mockedPostService.Object,
                                                                           mockedViewModelFactory.Object, mockedCloudinary.Object));
        }
Esempio n. 38
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var account = new CloudinaryDotNet.Account(
                this.configuration["Cloudinary:CloudName"],
                this.configuration["Cloudinary:ApiKey"],
                this.configuration["Cloudinary:ApiSecret"]);

            var cloudUtility = new Cloudinary(account);

            services.AddSingleton(cloudUtility);

            services.AddDbContext <ApplicationDbContext>(
                options => options.UseSqlServer(this.configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity <User>(IdentityOptionsProvider.GetIdentityOptions)
            .AddRoles <Role>().AddEntityFrameworkStores <ApplicationDbContext>();

            services.Configure <CookiePolicyOptions>(
                options =>
            {
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddControllersWithViews(
                options =>
            {
                options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            }).AddRazorRuntimeCompilation();
            services.AddRazorPages();

            services.AddSingleton(this.configuration);

            // Data repositories
            services.AddScoped(typeof(IDeletableEntityRepository <>), typeof(EfDeletableEntityRepository <>));
            services.AddScoped(typeof(IRepository <>), typeof(EfRepository <>));
            services.AddScoped <IDbQueryRunner, DbQueryRunner>();

            // Application services
            services.AddTransient <IEmailSender>(x => new SendGridEmailSender(this.configuration["SendGrid:ApiKey"]));
            services.AddTransient <IPhotoStorageService, PhotoStorageService>();
            services.AddTransient <IPhotoMetadataService, PhotoMetadataService>();
            services.AddTransient <IAlbumsService, AlbumsService>();
            services.AddTransient <ILicenseService, LicenseService>();
            services.AddTransient <IPhotoService, PhotoService>();
            services.AddTransient <IPhotoAlbumService, PhotoAlbumService>();
            services.AddTransient <ICommentService, CommentService>();
            services.AddTransient <IFavoritesService, FavoritesService>();
            services.AddTransient <ITopicReplyService, TopicReplyService>();
            services.AddTransient <ITopicService, TopicService>();
        }
        /// <summary>
        /// Method for uploading image from local host to cloudinary
        /// </summary>
        /// <param name="user"></param>
        /// <returns>Cloudinary link(string) of uploaded picture</returns>
        private string CloudinaryUpload(Models.RegisterBindingModel user)
        {
            var cloudPath = Server.MapPath(user.ProfileUrl);
            Account acount = new Account("gigantor", "986286566519458", "GT87e1BTMnfLut1_gXhSH0giZPg");
            Cloudinary cloudinary = new Cloudinary(acount);
            var uploadParams = new ImageUploadParams()
            {
                File = new FileDescription(cloudPath)
            };
            var uploadResult = cloudinary.Upload(uploadParams);

            string n = uploadResult.Uri.AbsoluteUri;
            return user.ProfileUrl = n;
        }
        /// <summary>
        /// Method for uploading image from local host to cloudinary
        /// </summary>
        /// <param name="user"></param>
        /// <returns>Cloudinary link(string) of uploaded picture</returns>
        private string CloudinaryUpload(Course course)
        {
            var cloudPath = System.Web.Hosting.HostingEnvironment.MapPath(course.PictureUrl);
            Account acount = new Account("gigantor", "986286566519458", "GT87e1BTMnfLut1_gXhSH0giZPg");
            Cloudinary cloudinary = new Cloudinary(acount);
            var uploadParams = new ImageUploadParams()
            {
                File = new FileDescription(cloudPath)
            };
            var uploadResult = cloudinary.Upload(uploadParams);

            string n = uploadResult.Uri.AbsoluteUri;
            return course.PictureUrl = n;

        }
Esempio n. 41
0
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            LinkButton Delete = (LinkButton)sender;
            string imageID = Delete.CommandArgument;

            HEWDataContext context = new HEWDataContext();
            ProjectsImage image = context.ProjectsImages.SingleOrDefault(i=>i.ID == int.Parse(imageID));

            Account account = new Account("dlyvxs7of", "634626974285569", "FtB_0jhcmFypFS7QTwCBKcPRGzE");
            Cloudinary cloudinary = new Cloudinary(account);
            cloudinary.DeleteResources(new [] {image.ImgPublicID});

            context.ProjectsImages.DeleteOnSubmit(image);
            context.SubmitChanges();

            rptImages.DataBind();
        }
Esempio n. 42
0
        internal static String uploadImage(string filePath, string publicID)
        {
            //CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary();
            //CloudinaryDotNet.Account account = new CloudinaryDotNet.Account("hmtca4hsp", "551419468127826", "6CRKqZzHmHxqCvpLaObNj2Hmsis");
            CloudinaryDotNet.Account account = new CloudinaryDotNet.Account("hiisiwhue", "579971361974369", "bHspTdlzXHwF3uoLrEu5yb9a0b0");

            CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);
            CloudinaryDotNet.Actions.ImageUploadParams uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams()
            {
                File = new CloudinaryDotNet.Actions.FileDescription(filePath),//@"C:\Users\David\Downloads\etgarPlusWebsite-master\etgarPlusWebsite\etgarPlus\images\1.png"),
                PublicId = publicID
            };

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

            string url = cloudinary.Api.UrlImgUp.BuildUrl(publicID + filePath.Substring(filePath.LastIndexOf(".")));
            return url;
        }
Esempio n. 43
0
        internal static String uploadImage(String filePath, String publicId) 
        {

            CloudinaryDotNet.Account account = new CloudinaryDotNet.Account("hmtca4hsp", "551419468127826", "6CRKqZzHmHxqCvpLaObNj2Hmsis");


            CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);
            CloudinaryDotNet.Actions.ImageUploadParams uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams()
            {
                File = new CloudinaryDotNet.Actions.FileDescription(filePath),//@"C:\Users\David\Downloads\etgarPlusWebsite-master\etgarPlusWebsite\etgarPlus\images\1.png"),
                PublicId = "4" //publicId
            };



            String url = cloudinary.Api.UrlImgUp.BuildUrl(publicId + filePath.Substring(filePath.LastIndexOf(".")));
            Debug.WriteLine(url);
            return url;
        }
Esempio n. 44
0
        public string UploadPhoto(Stream stream, int height, int width)
        {
            Account account = new Account(
              CLOUD_NAME,
               API_KEY,
              API_SECRET);

            Cloudinary cloudinary = new Cloudinary(account);
            var uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams()
            {
                File = new CloudinaryDotNet.Actions.FileDescription(Guid.NewGuid().ToString(), stream),
            };

            ImageUploadResult uploadResult = cloudinary.Upload(uploadParams);
            return
                cloudinary.Api.UrlImgUp.Transform(new Transformation().Width(width).Height(height).Crop("fill"))
                    .BuildUrl(String.Format("{0}.{1}", uploadResult.PublicId, uploadResult.Format));

        }
Esempio n. 45
0
        protected void UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
        {
            try
            {
                Account account = new Account("dlyvxs7of", "634626974285569", "FtB_0jhcmFypFS7QTwCBKcPRGzE");

                Cloudinary cloudinary = new Cloudinary(account);
                ImageUploadParams uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription("file", new MemoryStream(e.GetContents()))
                    };

                ImageUploadResult uploadResult = cloudinary.Upload(uploadParams);

                HEWDataContext context = new HEWDataContext();
                context.ProjectsImages.InsertOnSubmit(new ProjectsImage
                    {ImgPublicID = uploadResult.PublicId, ProjectID = int.Parse(Request.QueryString["ProjectID"])});
                context.SubmitChanges();
            }
            catch (Exception)
            {
            }
        }
Esempio n. 46
0
 public PhotoUploadService(Account account)
 {
     cloudinary = new Cloudinary(account);
     api = new Api(account);
 }
 public JsonResult Upload()
 {
     Account account = new Account(
                GlobalRes.CloudinaryCloud,
                GlobalRes.CloudinaryApi,
                GlobalRes.CloudinarySecret);
     CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);
     List<string> list = new List<string>();
     foreach (string file in Request.Files)
     {
         if (Request.Files[file] != null)
             list.Add(UploadImage(Request.Files[file], cloudinary));
     }
     foreach (string file in Request.Form)
     {
         if (Request.Form[file] != null)
             list.Add(UploadImageFabricJS(Request.Form[file], cloudinary));
     }
     return Json(list, JsonRequestBehavior.AllowGet);
 }
Esempio n. 48
0
        private string HandleFileUpload(ref Photo photo)
        {
            string filePath = @"~\Images\defaultAccomodationPhoto.jpg";

            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase file = Request.Files[0];
                if (file.ContentLength > 0 && _allowedTypes.Contains(file.ContentType))
                {
                    try
                    {
                        using (var bitmap = new Bitmap(file.InputStream))
                        {
                        }
                    }
                    catch
                    {
                        ModelState.AddModelError("PhotoUrl", "The file type is not supported");
                        return "none";
                    }

                    string fileName = Path.GetFileName(file.FileName);
                    filePath = Path.Combine(@"~\Images\Photos", fileName);
                    string fullPath = Path.Combine(Server.MapPath(@"~\Images\Photos"), fileName);
                    file.SaveAs(fullPath);

                    Account account = new Account(
                                  "bitbooking",
                                  "131162311141994",
                                  "yqy4VSrjuxaGeP8BUMgHwTozpfw");

                    Cloudinary cloudinary = new Cloudinary(account);

                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(fullPath)
                    };
                    var uploadResult = cloudinary.Upload(uploadParams);

                    FileInfo uploadedFileToServer = new FileInfo(fullPath);
                    uploadedFileToServer.Delete();

                    return uploadResult.Uri.AbsolutePath; //new photo URL from Cloudinary
                }
                else
                {
                    if (file.ContentLength > 0 && !_allowedTypes.Contains(file.ContentType))
                    {
                        ModelState.AddModelError("PhotoUrl", "The file type is not supported");
                        return "none";
                    }

                }
            }
            //photo.PhotoUrl = filePath;
            return filePath;
        }
        public ActionResult DeleteConfirmed(int id)
        {
            Course course = db.Courses.Find(id);
            db.Courses.Remove(course);
            db.SaveChanges();

            //this block of code deletes the image from cloudinary, after the course is deleted
            Account acount = new Account("gigantor", "986286566519458", "GT87e1BTMnfLut1_gXhSH0giZPg");
            Cloudinary cloudinary = new Cloudinary(acount);

            if (course.PictureUrl != null && course.PictureUrl.StartsWith("http://res.cloudinary.com/gigantor/image/upload/")) 
            {
                //this here is just a string manipulation to get to the ImageID from cloudinary
                string assist = "http://res.cloudinary.com/gigantor/image/upload/";
                string part1 = course.PictureUrl.Remove(course.PictureUrl.IndexOf(assist), assist.Length);
                string part2 = part1.Remove(0, 12);
                string toDelete = part2.Remove(part2.Length - 4);
                cloudinary.DeleteResources(toDelete);  //this finally deletes the image
            }
            return RedirectToAction("Index");
        }
Esempio n. 50
0
        public ActionResult Save(string t, string l, string h, string w, string fileName)
        {
            try
            {
                // Calculate dimensions
                var top = Convert.ToInt32(t.Replace("-", "").Replace("px", ""));
                var left = Convert.ToInt32(l.Replace("-", "").Replace("px", ""));
                var height = Convert.ToInt32(h.Replace("-", "").Replace("px", ""));
                var width = Convert.ToInt32(w.Replace("-", "").Replace("px", ""));

                // Get file from temporary folder
                var fn = Path.Combine(Server.MapPath(MapTempFolder), Path.GetFileName(fileName));
                // ...get image and resize it, ...
                var img = new WebImage(fn);
                img.Resize(width, height);
                // ... crop the part the user selected, ...
                img.Crop(top, left, img.Height - top - AvatarStoredHeight, img.Width - left - AvatarStoredWidth);
                // ... delete the temporary file,...
                System.IO.File.Delete(fn);
                // ... and save the new one.

                var newFileName = Path.GetFileName(fn);
                img.Save(Server.MapPath("~/" + newFileName));

                Account account = new Account(
                "lifedemotivator",
                "366978761796466",
                "WMYLmdaTODdm4U6VcUGhxapkcjI"
                );
                ImageUploadResult uploadResult = new ImageUploadResult();
                CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);
                var uploadParams = new ImageUploadParams()
                {
                    File = new FileDescription(Server.MapPath("~/" + newFileName)),
                    PublicId = User.Identity.Name + newFileName,
                };
                uploadResult = cloudinary.Upload(uploadParams);
                System.IO.File.Delete(Server.MapPath("~/" + newFileName));
                UrlAvatar = uploadResult.Uri.ToString();

                return Json(new { success = true, avatarFileLocation = UrlAvatar });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, errorMessage = "Unable to upload file.\nERRORINFO: " + ex.Message });
            }
        }
Esempio n. 51
0
        public ActionResult SaveUploadedFile()
        {
            bool isSavedSuccessfully = true;
            string fName = "";
            string str = "";
            try
            {
                foreach (string fileName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[fileName];
                    //Save file content goes here
                    fName = file.FileName;
                    
                    if (file != null && file.ContentLength > 0)
                    {

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

                        string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");

                        var fileName1 = Path.GetFileName(file.FileName);

                        bool isExists = System.IO.Directory.Exists(pathString);

                        if (!isExists)
                            System.IO.Directory.CreateDirectory(pathString);

                        var path = string.Format("{0}\\{1}", pathString, file.FileName);
                        file.SaveAs(path);
                        Account account = new Account(
                            "kuzzya",
                            "649899148786625",
                            "Em9LZocDSzlf5Jf9ikhTRKwvuhY");

                        Cloudinary cloudinary = new Cloudinary(account);
                        var uploadParams = new ImageUploadParams()
                        {
                            File = new FileDescription(path)
                        };
                        var uploadResult = cloudinary.Upload(uploadParams);
                        str = uploadResult.Uri.AbsoluteUri;
                    }

                }

            }
            catch (Exception ex)
            {
                isSavedSuccessfully = false;
            }


            if (isSavedSuccessfully)
            {
                //return Json(new { Message = fName });
                return Json(new { Message = "Successful", name = str });
            }
            else
            {
                return Json(new { Message = "Error in saving file" });
            }
        }
Esempio n. 52
0
 public ImageService()
 {
     Account account = new Account("dsvsc4z0s", "357469842567916", "WEBAf00otXulq3kliKYsFfEwBYE");
     this.cloud = new Cloudinary(account);
 }
        public JsonResult Upload()
        {
            List<ImageUploadResult> list = new List<ImageUploadResult>();
            JsonResult trem = new JsonResult();
            string fileName = "";
            ImageUploadResult uploadResult = new ImageUploadResult();
            ImageUploadResult uploadResult2 = new ImageUploadResult();
            ImageUploadParams uploadParams = new ImageUploadParams();
            ImageUploadParams uploadParams2 = new ImageUploadParams();
            Account account = new Account(
                       "aniknaemm",
                       "173434464182424",
                       "p3LleRLwWAxpm9yU3CHT63qKp_E");

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

            foreach (string file in Request.Files)
            {
                var upload = Request.Files[file];
                if (upload != null)
                {                   
                    fileName = System.IO.Path.GetFileName(upload.FileName);
                    upload.SaveAs(Server.MapPath("~/" + fileName));
                    uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(Server.MapPath("~/" + fileName)),
                        PublicId = User.Identity.Name + fileName,
                    };        
                }
            }


            foreach (string file in Request.Form)
            {
                var upload = Request.Form[file];
                if (upload != null)
                {

                    string x = upload.Replace("data:image/png;base64,", "");
                    byte[] imageBytes = Convert.FromBase64String(x);
                    MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);


                    ms.Write(imageBytes, 0, imageBytes.Length);
                    System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
                    image.Save(Server.MapPath("~/img.png"), System.Drawing.Imaging.ImageFormat.Png);

                    uploadParams2 = new ImageUploadParams()
                    {
                        File = new FileDescription(Server.MapPath("~/img.png")),
                        PublicId = User.Identity.Name + fileName +"demotevators"
                    };
                }
            }


            uploadResult = cloudinary.Upload(uploadParams);
            list.Add(uploadResult);
            uploadResult2 = cloudinary.Upload(uploadParams2);
            list.Add(uploadResult2);
            System.IO.File.Delete(Server.MapPath("~/" + fileName));
            System.IO.File.Delete(Server.MapPath("~/img.png"));
            return Json(list, JsonRequestBehavior.AllowGet);
        }
 public CloudinaryHelper()
 {
     account = new Account (CLOUD_NAME, API_KEY, API_SECRET);
     cloudinary = new Cloudinary (account);
 }
Esempio n. 55
0
        /// <summary>
        /// Uploads image on cloudinary
        /// </summary>
        /// <returns></returns>
        private string UploadImage()
        {
            Account account = new Account("dvnnqotru", "252251816985341", "eqxRrtlVyiWA5-WCil_idtLzP6c");
            Cloudinary cloudinary = new Cloudinary(account);

            if (Request.Files.Count > 0)  //is there file to upload
            {
                HttpPostedFileBase file = Request.Files[0];
                if (file.ContentLength > 0 && _allowedTypes.Contains(file.ContentType))
                {
                    try  //test is selected file a image
                    {
                        using (var bitmap = new Bitmap(file.InputStream))
                        {
                            if (bitmap.Width < 110 || bitmap.Height < 140)  //minimum size of picture is 110x140
                            {
                                ModelState.AddModelError("PictureUrl", "Picture is too small");
                                return null;
                            }
                        }
                    }
                    catch
                    {
                        ModelState.AddModelError("PictureUrl", "The file type is not supported");
                        return null;
                    }

                    file.SaveAs(Path.Combine(Server.MapPath("~/Content/"), file.FileName));

                    var uploadParams = new ImageUploadParams()  //upload to cloudinary
                    {
                        File = new FileDescription(Path.Combine(Server.MapPath("~/Content/"), file.FileName)),
                        Transformation = new Transformation().Crop("fill").Width(110).Height(140)

                    };

                    var uploadResult = cloudinary.Upload(uploadParams);
                    System.IO.File.Delete(Path.Combine(Server.MapPath("~/Content/"), file.FileName));
                    return uploadResult.Uri.AbsolutePath;
                }
                else
                {
                    ModelState.AddModelError("PictureUrl", "The file type is not supported");
                    return null;
                }
            }
            return null;
        }
 public CloudinaryStorage()
 {
     Account account = new Account(cloudName, apiKey, apiSecret);
     cloudinary = new Cloudinary(account);
 }
 private Cloudinary getCloudinary()
 {
     var account = new Account(Globals.CloudinaryName, Globals.CloudinaryAPIKey, Globals.CloudinarySecret);
     return new Cloudinary(account);
 }
Esempio n. 58
0
        private static string SanitiseImagesAndLinks(string content, Options options)
        {
            Account cloudinaryAccount = new Account(options.CloudinaryCloudName, options.CloudinaryApiKey, options.CloudinaryApiSecret);
            Cloudinary cloudinary = new Cloudinary(cloudinaryAccount);

            // Look for relative Urls
            string srcRegex = "(src=[\"'])(/posts/files/|https?://www.gregpakes.co.uk/posts/files/)(.+?)([\"'].*?)";
            //string hrefRegex = "(href=[\"'])(/posts/files/||http://www.gregpakes.co.uk/posts/files/)(.+?)([\"'].*?)";

            foreach (Match match in Regex.Matches(content, srcRegex))
            {

                // Loop through the matches
                // Get the image and then upload to cloudinary
                var localPath = string.Format("files\\{0}", match.Groups[3].Value.Replace("/", "\\"));
                var fullPath = Path.Combine(options.InputDirectory, localPath);
                var decodedFullPath = HttpUtility.UrlDecode(fullPath);
                string finalPath = null;
                if (!File.Exists(decodedFullPath))
                {
                    if (!File.Exists(fullPath))
                    {
                        throw new Exception("Image not found");
                    }
                    else
                    {
                        finalPath = fullPath;
                    }
                }
                else
                {
                    finalPath = decodedFullPath;
                }

                if (finalPath != null)
                {
                    Logger.Log("Uploading {0} to cloudinary.", finalPath);
                    // Upload file to Cloudinary
                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(finalPath)
                    };
                    var uploadResult = cloudinary.Upload(uploadParams);
                    var replacementUri = uploadResult.SecureUri;

                    // Should cover all urls
                    content = content.Replace(match.Groups[2].Value + match.Groups[3].Value, replacementUri.ToString());
                }

            }

            //content = Regex.Replace(content, hrefRegex, "$1/images/$3$4");

            return content;
        }
Esempio n. 59
0
        private string UploadImg(string picPublicId)
        {
            byte[] imageBytes = Convert.FromBase64String(hdnImage.Value);
            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

            Account account = new Account("dlyvxs7of", "634626974285569", "FtB_0jhcmFypFS7QTwCBKcPRGzE");

            Cloudinary cloudinary = new Cloudinary(account);
            if (!string.IsNullOrEmpty(picPublicId))
                cloudinary.DeleteResources(new string[] {picPublicId});

            ImageUploadParams uploadParams = new ImageUploadParams()
            {
                File = new FileDescription("file", ms),
            };

            ImageUploadResult result = cloudinary.Upload(uploadParams);
            return result.PublicId;
        }
Esempio n. 60
0
 /// <summary>
 /// Parameterized constructor
 /// </summary>
 /// <param name="account">Cloudinary account</param>
 public Cloudinary(Account account)
 {
     m_api = new Api(account);
 }