Ejemplo 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));
        }
Ejemplo n.º 2
1
        public ActionResult Task(HttpPostedFileBase fileUpload, HttpPostAttribute selboton)
        {
            if (fileUpload == null)
            {
                return View(GetImageCollection());
            }

            var cloudinary = new Cloudinary(
            new Account(
            "raisky",
            "712813241936831",
            "Z9cprR-2l0R51ehGj5PIsUr2d3I"));

            var uploadParams = new ImageUploadParams()
            {
                File = new FileDescription(fileUpload.FileName, fileUpload.InputStream),
            };

            var uploadResult = cloudinary.Upload(uploadParams);

            var uplPath = uploadResult.Uri;

            Image uploadedImage = new Image();
            uploadedImage.Path = uplPath.AbsoluteUri;
            uploadedImage.User = User.Identity.Name;
            uploadedImage.PublicId = uploadResult.PublicId;

            imageDataBase.Entry(uploadedImage).State = System.Data.Entity.EntityState.Added;
            imageDataBase.SaveChanges();

            return View(GetImageCollection());
        }
Ejemplo n.º 3
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);
        }
Ejemplo n.º 4
0
        public JsonResult Upload()
        {
            JsonResult        trem         = new JsonResult();
            ImageUploadResult uploadResult = new ImageUploadResult();

            foreach (string file in Request.Files)
            {
                var upload = Request.Files[file];
                if (upload != null)
                {
                    Account account = new Account(
                        "demcloud",
                        "713675365492318",
                        "1mGY2GOZR0FQ-qivH-p8BRsUZCs");

                    CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);
                    // получаем имя файла
                    string fileName = System.IO.Path.GetFileName(upload.FileName);
                    // сохраняем файл в папку Files в проекте
                    upload.SaveAs(Server.MapPath("~/" + fileName));
                    var uploadParams = new ImageUploadParams()
                    {
                        File     = new FileDescription(Server.MapPath("~/" + fileName)),
                        PublicId = User.Identity.Name + fileName,
                        Tags     = "special, for_homepage"
                    };

                    uploadResult = cloudinary.Upload(uploadParams);
                    System.IO.File.Delete(Server.MapPath("~/" + fileName));
                }
            }
            return(Json(uploadResult, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
0
        public static Images upload(WebImage webImage, string folder = "")
        {
            try
            {
                CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(CloudAccount);
                byte[] fileData = webImage.GetBytes();

                using (MemoryStream memoryStream = new MemoryStream(fileData))
                {
                    ImageUploadParams uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription("advert images", memoryStream),
                        Transformation = new Transformation().Crop("limit").Width(750).Height(750),
                        Tags           = "advert_image",
                        Folder         = folder
                    };
                    Dictionary <string, object> dic = JsonHelper.JsonHelper.ConvertJsonToDictionary(cloudinary.Upload(uploadParams).JsonObj.ToString());
                    Images image = new Images()
                    {
                        url = getParam(dic, "public_id") + "." + getParam(dic, "format")
                    };
                    return(image);
                };
            }
            catch (System.Exception ex)
            {
                return(null);
            }
        }
Ejemplo n.º 7
0
        public PhotoAccessor(IOptions <CloudinarySettings> config)
        {
            var acc = new Account
                          (config.Value.CloudName, config.Value.ApiKey, config.Value.ApiSecret);

            _cloudinary = new CloudinaryDotNet.Cloudinary(acc);
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
0
        public async Task <string> UploadPicture()
        {
            var logic   = new UserProfileLogic(db);
            var athlete = logic.GetAthleteForUserName(User.Identity.Name);

            var file = await Request.Content.ReadAsStreamAsync();

            if (file.Length < 100)
            {
                throw new Exception("file.Length=" + file.Length.ToString());
            }
            if (file.Length > 1000000 * 100)
            {
                throw new Exception("file.Length=" + file.Length.ToString());
            }

            string cloudinaryAccount = System.Web.Configuration.WebConfigurationManager.AppSettings["CloudinaryAccount"];
            string cloudinaryKey     = System.Web.Configuration.WebConfigurationManager.AppSettings["CloudinaryKey"];
            string cloudinarySecret  = System.Web.Configuration.WebConfigurationManager.AppSettings["CloudinarySecret"];
            var    cloudinary        = new CloudinaryDotNet.Cloudinary(new CloudinaryDotNet.Account(cloudinaryAccount, cloudinaryKey, cloudinarySecret));

            var uploadResult = await cloudinary.UploadAsync(new CloudinaryDotNet.Actions.ImageUploadParams()
            {
                File           = new CloudinaryDotNet.Actions.FileDescription("athlete" + athlete.AthleteID, file),
                Transformation = new Transformation().Width(500).Height(500).Crop("limit") // limit image size to 500x500 max
            });

            //string pictureUrl = uploadResult.Uri.ToString();
            string pictureUrl = "http://res.cloudinary.com/bestmybest/image/upload/" + uploadResult.PublicId + "." + uploadResult.Format;

            new UserProfileLogic(db).UpdateAthletePicture(athlete.AthleteID, pictureUrl);

            return(pictureUrl);
        }
Ejemplo n.º 10
0
        public virtual void Initialize()
        {
            var builder = new ConfigurationBuilder();

            builder.SetBasePath(Directory.GetCurrentDirectory());
            builder.AddJsonFile("appsettings.json");
            var config = builder.Build();

            m_appveyor_job_id = Environment.GetEnvironmentVariable("APPVEYOR_JOB_ID");
            m_suffix          = String.IsNullOrEmpty(m_appveyor_job_id) ? new Random().Next(100000, 999999).ToString() : m_appveyor_job_id;
            m_test_tag       += m_suffix;
            m_cloudName       = config.GetSection("AccountSettings:CloudName").Value;
            m_apiKey          = config.GetSection("AccountSettings:ApiKey").Value;
            m_apiSecret       = config.GetSection("AccountSettings:ApiSecret").Value;
            m_apiBaseAddress  = config.GetSection("AccountSettings:ApiBaseAddress").Value;

            m_testVideoPath      = Path.Combine(Path.GetDirectoryName(typeof(IntegrationTestBase).GetTypeInfo().Assembly.Location), TEST_MOVIE);
            m_testImagePath      = Path.Combine(Path.GetDirectoryName(typeof(IntegrationTestBase).GetTypeInfo().Assembly.Location), TEST_IMAGE);
            m_testLargeImagePath = Path.Combine(Path.GetDirectoryName(typeof(IntegrationTestBase).GetTypeInfo().Assembly.Location), TEST_LARGEIMAGE);
            m_testPdfPath        = Path.Combine(Path.GetDirectoryName(typeof(IntegrationTestBase).GetTypeInfo().Assembly.Location), TEST_PDF);
            m_testIconPath       = Path.Combine(Path.GetDirectoryName(typeof(IntegrationTestBase).GetTypeInfo().Assembly.Location), TEST_FAVICON);

            m_account    = GetAccountInstance();
            m_cloudinary = GetCloudinaryInstance(m_account);

            SaveEmbeddedToDisk(TEST_IMAGE, m_testImagePath);
            SaveEmbeddedToDisk(TEST_LARGEIMAGE, m_testLargeImagePath);
            SaveEmbeddedToDisk(TEST_MOVIE, m_testVideoPath);
            SaveEmbeddedToDisk(TEST_FAVICON, m_testIconPath);
            SaveEmbeddedToDisk(TEST_PDF, m_testPdfPath);
        }
Ejemplo n.º 11
0
        public void AgregarImagenTarea(IEnumerable <HttpPostedFileBase> Imagen, int IdTarea)
        {
            FotosBO  FotBO    = new FotosBO();
            FotosDAO DAOFotos = new FotosDAO();

            FotBO.CodigoTarea = IdTarea;
            if (Imagen != null)
            {
                foreach (var item in Imagen)
                {
                    Account account = new Account("collegejob", "668222543257229", "KmLmrbmSfDXVabsyzcFHQxKdiIE");

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

                    var uploadParams = new ImageUploadParams
                    {
                        File = new FileDescription(item.FileName, item.InputStream),
                    };

                    var uploadResult = cloudinary.Upload(uploadParams);

                    string ruta = uploadResult.SecureUri.ToString();

                    FotBO.Imagen = ruta;
                    DAOFotos.AgregarFoto(FotBO);
                }
            }
        }
        private List <SearchResource> GetResources(string tag, int totalCount)
        {
            var cloudinary = new CloudinaryDotNet.Cloudinary(new Account(_cloudinaryOptions.CloudName,
                                                                         _cloudinaryOptions.ApiKey, _cloudinaryOptions.ApiSecret));
            var    resources  = new List <SearchResource>();
            string?nextCursor = null;

            do
            {
                var requestSize = Math.Min(totalCount, 500);
                var results     = cloudinary.Search()
                                  .Expression($"tags={tag}")
                                  .MaxResults(requestSize)
                                  .NextCursor(nextCursor)
                                  .Execute();
                resources.AddRange(results.Resources);
                totalCount -= 500;
                nextCursor  = results.NextCursor;
                if (results.Resources.Count == 0 || results.Resources.Count != requestSize)
                {
                    break;
                }
            } while (totalCount > 0);

            return(resources);
        }
        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;
        }
        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;
        }
Ejemplo n.º 15
0
 public static void Init()
 {
     Account account = new Account(
     "rockitshipshawty",
     "969736378743428",
     "SouveLJZlKhFpf2B01Qm80bV_9E");
     Cloudinary = new Cloudinary(account);
 }
Ejemplo n.º 16
0
        public CloudinaryHelper(IConfiguration configuration)
        {
            _configuration     = configuration;
            _cloudinaryOptions = _configuration.GetSection("CloudinaryOptions").Get <CloudinaryOptions>();
            Account account = new Account(_cloudinaryOptions.CloudName, _cloudinaryOptions.ApiKey, _cloudinaryOptions.ApiSecret);

            _cloudinary = new CloudinaryDotNet.Cloudinary(account);
        }
 public CloudinaryImageUploader()
 {
     _account = new Account()
     {
         ApiKey = ApiKey, ApiSecret = ApiSecret, Cloud = CloudName
     };
     _cloudinary = new CloudinaryDotNet.Cloudinary(_account);
 }
Ejemplo n.º 18
0
        public CloudinaryPhotoManager()
        {
            var account = new Account(
 "my_cloud_name",
 "my_api_key",
 "my_api_secret");
            _cloudinary = new Cloudinary(account);
        }
Ejemplo n.º 19
0
 public CloudinaryProvider(IConfiguration configuration)
 {
     this._configuration = configuration;
     this._account       = new Account(
         this._configuration.GetValue <string>("Cloudinary:CloudName"),
         this._configuration.GetValue <string>("Cloudinary:APIKey"),
         this._configuration.GetValue <string>("Cloudinary:APISecret"));
     this._cloudinary = new CloudinaryDotNet.Cloudinary(this._account);
 }
Ejemplo n.º 20
0
        public Tests()
        {
            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CLOUDINARY_URL")))
            {
                throw new Exception("CLOUDINARY_URL should be set");
            }

            Cloudinary = new CloudinaryDotNet.Cloudinary();
        }
Ejemplo n.º 21
0
 /// <summary>
 /// A convenient method for initialization of new Cloudinary instance with necessary checks
 /// </summary>
 /// <param name="account">Instance of Account</param>
 /// <returns>New Cloudinary instance</returns>
 public CloudinaryDotNet.Cloudinary GetCloudinaryInstance(Account account)
 {
     CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);
     if (!String.IsNullOrWhiteSpace(m_apiBaseAddress))
     {
         cloudinary.Api.ApiBaseAddress = m_apiBaseAddress;
     }
     return(cloudinary);
 }
Ejemplo n.º 22
0
        public CloudinaryUploader()
        {
            var cloudName = ConfigurationManager.AppSettings["CloudinaryCloudName"];
            var apiKey    = ConfigurationManager.AppSettings["CloudinaryApiKey"];
            var apiSecret = ConfigurationManager.AppSettings["CloudinaryApiSecret"];
            var account   = new Account(cloudName, apiKey, apiSecret);

            cloudinary = new CloudinaryDotNet.Cloudinary(account);
        }
Ejemplo n.º 23
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);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Constructor method.
        /// </summary>
        /// <param name="cloudName">The cloudinary account cloud name.</param>
        public CloudinaryThumbService(string cloudName)
        {
            cloudName = cloudName ?? throw new ArgumentNullException(nameof(cloudName), nameof(CloudinaryThumbService));

            _client = new CloudinaryDotNet.Cloudinary(
                new Account(
                    cloudName
                    )
                );
        }
Ejemplo n.º 25
0
        public CloudinaryServices(IOptions <CloudinarySettings> cloudinaryConfigOptions)
        {
            Account acc = new Account(
                cloudinaryConfigOptions.Value.CloudName,
                cloudinaryConfigOptions.Value.ApiKey,
                cloudinaryConfigOptions.Value.ApiSecret
                );

            _cloudinary = new CloudinaryDotNet.Cloudinary(acc);
        }
Ejemplo n.º 26
0
        public ActionResult ActualizarUsuario(string ID, string Tipo2, string Tipo, string Nombre, string Apellidos, string Direccion, string Correo, string Contraseña, string FechaNac, string Telefono, byte[] img, HttpPostedFileBase Imagen)
        {
            UsuarioBO ObjDatos = new UsuarioBO();

            if (Imagen != null)
            {
                //ObjDatos.Imagen = new byte[Imagen.ContentLength];
                //Imagen.InputStream.Read(ObjDatos.Imagen, 0, Imagen.ContentLength);

                Account account = new Account("collegejob", "668222543257229", "KmLmrbmSfDXVabsyzcFHQxKdiIE");

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

                var uploadParams = new ImageUploadParams
                {
                    File = new FileDescription(Imagen.FileName, Imagen.InputStream),
                };

                var uploadResult = cloudinary.Upload(uploadParams);

                string ruta = uploadResult.SecureUri.ToString();

                ObjDatos.ImagenUrl = ruta;
            }
            else
            {
                ObjDatos.Imagen = img;
            }

            if (Tipo != null)
            {
                ObjDatos.TipoUsuario = int.Parse(Tipo);
            }
            else
            {
                ObjDatos.TipoUsuario = int.Parse(Tipo2);
            }

            ObjDatos.Codigo     = int.Parse(ID);
            ObjDatos.Nombre     = Nombre;
            ObjDatos.Apellidos  = Apellidos;
            ObjDatos.Direccion  = Direccion;
            ObjDatos.Email      = Correo;
            ObjDatos.Contraseña = Contraseña;
            ObjDatos.FechaNac   = Convert.ToDateTime(FechaNac);
            ObjDatos.Telefono   = long.Parse(Telefono);

            int CodAct = ObjUsuario.ActualizarUsuario2(ObjDatos);

            Session["Actualizar"] = CodAct;
            ViewBag.Actualizar    = CodAct;
            BuscarView(null);
            return(View("BuscarView"));
        }
Ejemplo n.º 27
0
        public CloudinaryStorage(ICloudinaryConfiguration configuration)
        {
            _configuration = configuration;

            var account = new Account(
                _configuration.CloudName,
                _configuration.ClientKey,
                _configuration.ClientSecret);

            _cloudinary = new CloudinaryDotNet.Cloudinary(account);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// create a new image factory using our cloudinary details
        /// </summary>
        /// <param name="accountName"></param>
        /// <param name="apiKey"></param>
        /// <param name="apiSecret"></param>
        public ImageFactory(string accountName, string apiKey, string apiSecret)
        {
            if (string.IsNullOrEmpty(accountName))
                throw new ArgumentException("accountName parameter cannot be null or empty");
            if (string.IsNullOrEmpty(apiKey))
                throw new ArgumentException("apiKey parameter cannot be null or empty");
            if (string.IsNullOrEmpty(apiSecret))
                throw new ArgumentException("apiSecret parameter cannot be null or empty");

            _cloudinary = new Cloudinary(new Account(accountName,apiKey,apiSecret));
        }
Ejemplo n.º 29
0
        public CloudinaryService(IOptions <CloudinaryOptions> options)
        {
            this.options = options.Value;

            var account = new Account(
                this.options.CloudName,
                this.options.ApiKey,
                this.options.ApiSecret);

            this.cloudinary = new CloudinaryDotNet.Cloudinary(account);
        }
Ejemplo n.º 30
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);
        }
 public CloudinaryRequest()
 {
     Cloudinary = new Cloudinary
     (
         new Account
         (
             ConfigurationManager.AppSettings["cloudinary:Cloud"],
             ConfigurationManager.AppSettings["cloudinary:ApiKey"],
             ConfigurationManager.AppSettings["cloudinary:ApiSecret"]
         )
     );
 }
Ejemplo n.º 32
0
        public Task DeleteAsync(string imageUrl)
        {
            var cloudinary = new CloudinaryDotNet.Cloudinary(new Account(_options.CloudName,
                                                                         _options.ApiKey, _options.ApiSecret));

            // TODO: This is not safe, we should not do this
            var publicId = Path.GetFileNameWithoutExtension(imageUrl);

            var deleteParams = new DeletionParams(publicId);

            return(cloudinary.DestroyAsync(deleteParams));
        }
Ejemplo n.º 33
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient <IGroupsService, GroupsService>();
            services.AddTransient <IStudentsService, StudentsService>();
            services.AddTransient <ITeachersService, TeachersService>();
            services.AddTransient <IParentsService, ParentsService>();
            services.AddTransient <IPaymentsService, PaymentsService>();
            services.AddTransient <ILevelsService, LevelsService>();
            services.AddTransient <ICloudinaryService, Services.External.CloudinaryService.CloudinaryService>();
            services.AddTransient <IApplicationUserService, ApplicationUserService>();

            services.AddDbContext <KidsManagementDbContext>(options =>
                                                            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity <ApplicationUser>
                (options =>
            {
                options.SignIn.RequireConfirmedAccount  = false;
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequiredLength         = 2;
                options.Password.RequiredUniqueChars    = 0;
            })
            .AddRoles <ApplicationRole>()
            .AddEntityFrameworkStores <KidsManagementDbContext>()
            //.AddUserStore<KidsManagementDbContext>() the above statement adds them both i think
            //.AddRoleStore<KidsManagementDbContext>()
            .AddDefaultTokenProviders();

            services.AddRazorPages();
            services.AddRazorPages().AddSessionStateTempDataProvider();

            services.AddControllersWithViews(configure =>
            {
                configure.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            });
            services.AddControllersWithViews().AddSessionStateTempDataProvider();
            services.AddSession();


            //External Services

            Account account = new Account(
                this.Configuration["Cloudinary:Cloud_Name"],
                this.Configuration["Cloudinary:API_Key"],
                this.Configuration["Cloudinary:API_Secret"]);

            CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);
            services.AddSingleton(cloudinary);
        }
Ejemplo n.º 34
0
        public virtual CloudinaryDotNet.Cloudinary GetCloudinaryInstance(CloudinaryIdentityObject credentials)
        {
            var account = new Account()
            {
                ApiKey    = credentials.ApiKey,
                ApiSecret = credentials.ApiSecret,
                Cloud     = credentials.CloudName
            };

            var instance = new CloudinaryDotNet.Cloudinary(account);

            return(instance);
        }
Ejemplo n.º 35
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);
            }
        }
Ejemplo n.º 36
0
        public MovieController(ApplicationDbContext context, IOptions <CloudinarySettings> cloudConfig, IMapper mapper)
        {
            _mapper  = mapper;
            _context = context;
            var     cloudConfig1 = cloudConfig;
            Account acc          = new Account(
                cloudConfig1.Value.CloudName,
                cloudConfig1.Value.ApiKey,
                cloudConfig1.Value.ApiSecret
                );

            _cloudinary = new CloudinaryDotNet.Cloudinary(acc);
        }
Ejemplo n.º 37
0
        public PhotoController(DataContext context,
                               IMapper mapper,
                               IOptions <CloudinarySettings> cloudinaryConfig)
        {
            _context          = context;
            _mapper           = mapper;
            _cloudinaryConfig = cloudinaryConfig;
            Account account = new Account(_cloudinaryConfig.Value.CloudName,
                                          _cloudinaryConfig.Value.ApiKey,
                                          _cloudinaryConfig.Value.ApiSecret);

            _cloudinary = new CloudinaryDotNet.Cloudinary(account);
        }
Ejemplo n.º 38
0
        public virtual CloudinaryDotNet.Cloudinary GetCloudinaryInstance(CloudinaryIdentityObject credentials)
        {
            var result  = _credentialsService.GetRestApiCredentials(credentials);
            var account = new Account()
            {
                ApiKey    = result.Key,
                ApiSecret = result.Secret,
                Cloud     = credentials.CloudName
            };

            var instance = new CloudinaryDotNet.Cloudinary(account);

            return(instance);
        }
Ejemplo n.º 39
0
        public void DeleteCloudinaryRecipeImage(string imageName)
        {
            CloudinaryDotNet.Cloudinary cloudinaryDelete = new CloudinaryDotNet.Cloudinary(cloudinaryAccount);

            var delParams = new DelResParams()
            {
                PublicIds = new List <string>()
                {
                    Path.GetFileNameWithoutExtension(imageName)
                },
                Invalidate = true
            };
            DelResResult result = cloudinaryDelete.DeleteResources(delParams);
        }
        /// <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;
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Constructor method.
        /// </summary>
        /// <param name="cloudName">Cloudinary cloud name.</param>
        /// <param name="cloudApiKey">Cloudinary api key.</param>
        /// <param name="cloudApiSecret">Cloudinary api secret.</param>
        public CloudinaryStorageService(string cloudName, string cloudApiKey, string cloudApiSecret)
        {
            cloudName      = cloudName ?? throw new ArgumentNullException(nameof(cloudName), nameof(CloudinaryStorageService));
            cloudApiKey    = cloudApiKey ?? throw new ArgumentNullException(nameof(cloudApiKey), nameof(CloudinaryStorageService));
            cloudApiSecret = cloudApiSecret ?? throw new ArgumentNullException(nameof(cloudApiSecret), nameof(CloudinaryStorageService));

            _client = new CloudinaryDotNet.Cloudinary(
                new Account(
                    cloud: cloudName,
                    apiKey: cloudApiKey,
                    apiSecret: cloudApiSecret
                    )
                );
        }
        /// <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;

        }
Ejemplo n.º 43
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();
        }
Ejemplo n.º 44
0
        public ActionResult DeleteImage(int id)
        {
            Image imageToDelete = imageDataBase.Images.Find(id);
            DelResParams deleteParams = new DelResParams()
            {
                PublicIds = new System.Collections.Generic.List<String>() { imageToDelete.PublicId },
                Invalidate = true
            };
            Cloudinary cloudinary = new Cloudinary(new Account(
            "raisky",
            "712813241936831",
            "Z9cprR-2l0R51ehGj5PIsUr2d3I"));

            cloudinary.DeleteResources(deleteParams);
            imageDataBase.Entry(imageToDelete).State = System.Data.Entity.EntityState.Deleted;
            imageDataBase.SaveChanges();
            return RedirectToAction("Task");
        }
Ejemplo n.º 45
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;
        }
Ejemplo n.º 46
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;
        }
Ejemplo n.º 47
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));

        }
Ejemplo n.º 48
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)
            {
            }
        }
Ejemplo n.º 49
0
 public Model(Cloudinary cloudinary)
 {
     Cloudinary = cloudinary;
 }
Ejemplo n.º 50
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;
        }
Ejemplo n.º 51
0
 public PhotoUploadService(Account account)
 {
     cloudinary = new Cloudinary(account);
     api = new Api(account);
 }
Ejemplo n.º 52
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;
        }
Ejemplo n.º 53
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 });
            }
        }
Ejemplo n.º 54
0
 public DictionaryModel(Cloudinary cloudinary, Dictionary<string, string> dict)
     : base(cloudinary)
 {
     Dict = dict;
 }
        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);
        }
Ejemplo n.º 56
0
 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);
 }
Ejemplo n.º 57
0
 public PhotosModel(Cloudinary cloudinary, List<Photo> photos)
     : base(cloudinary)
 {
     Photos = photos;
 }
 public CloudinaryStorage()
 {
     Account account = new Account(cloudName, apiKey, apiSecret);
     cloudinary = new Cloudinary(account);
 }
Ejemplo n.º 59
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" });
            }
        }
Ejemplo n.º 60
-1
        // NOTE: Secrets.cs contains the definitions for CLOUD_NAM, API_KEY and API_SECRET
        public static string AddPhoto(Stream photoStream)
        {
            var cloudinary = new Cloudinary(new Account(CLOUD_NAME, API_KEY, API_SECRET));

            ImageUploadResult result = cloudinary.Upload(new ImageUploadParams {
                File = new FileDescription("my-image.jpg", photoStream),
            });

            if (result.Error != null)
                throw new Exception(result.Error.Message);

            return result.Uri.ToString();
        }