public ActionResult UploadNewFiles(FineUpload upload, string extraParam1, int?extraParam2)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var owner = ((MyMembershipProvider)Membership.Provider).GetUserByEmail(User.Identity.Name);

            if (owner == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var fileName      = Path.GetFileNameWithoutExtension(upload.FileName);
            var fileExtension = Path.GetExtension(upload.FileName);

            if (string.IsNullOrWhiteSpace(fileName) || string.IsNullOrWhiteSpace(fileExtension))
            {
                return(new FineUploaderResult(false, error: "The file or file name is empty!"));
            }

            var fullName = fileName.ToHashedString() + fileExtension;

            var fileSectionNumber = int.Parse(upload.FileSection);

            var ipAdress = ConfigurationManager.AppSettings["Server"];

            var filePath = string.Format(@"d:\UploadFiles\{0}\{1}", fileSectionNumber, fullName);

            //var pathToSave = Path.Combine(ipAdress, filePath);
            var pathToSave = string.Format(@"{0}\{1}", ipAdress, filePath);

            if (System.IO.File.Exists(pathToSave))
            {
                return(new FineUploaderResult(false, error: "The same file is already exists!"));
            }

            var fileSize = upload.InputStream.Length;

            upload.SaveAs(pathToSave);

            var fileSection = _homeService.GetFileSectionById(fileSectionNumber);

            try
            {
                _fileService.AddFile(fileName, fullName, fileSize, filePath, ipAdress, fileSection, owner);
            }
            catch (DataException ex)
            {
                return(new FineUploaderResult(false, error: ex.Message));
            }

            return(new FineUploaderResult(true, new { message = "Upload is finished successfully!" }));
        }
Exemple #2
0
        public virtual ActionResult UploadFileCollectionItem(FineUpload upload, int id, string propName, int parentId)
        {
            // id - айдишник корневого элемента, который мы сейчас редактируем
            // parentId - айдишник элемента, которому принадлежит файл (элемента в коллекции)
            // propName - полный путь к элементу и файлу (root.items.innerCollection.File, например)

            // каким-то образом мне надо добраться до элемента

            //var root = Repository.GetByPrimaryKey(id);
            //propName
            if (upload.InputStream != null && upload.InputStream.Length != 0)
            {
                try
                {
                    var entity   = Repository.GetByPrimaryKey(id);
                    var path     = propName.Split('.');
                    var parent   = GetParent(entity, path, 0, parentId);      // возвращает элемент коллекции innerCollection с id=parentId
                    var fileprop = path[path.Length - 1];                     // свойство в котором хранится файл
                    var file     = (IFileEntity)TypeHelpers.GetPropertyValue(parent, fileprop);
                    var settings = Settings.GetFormSettingsItem(propName);
                    if (file == null)
                    {
                        var propType = TypeHelpers.GetPropertyType(parent, fileprop);
                        file = (IFileEntity)Activator.CreateInstance(propType);
                        ((IObjectContextAdapter)Repository.DataContext).ObjectContext.AddObject(TypeHelpers.GetEntitySetName(file, Repository.DataContext), file);
                        TypeHelpers.SetPropertyValue(parent, fileprop, file);
                    }

                    DefaultFileService.DeleteFile(file, HttpContext);
                    var defaultPath = AppConfig.GetValue(AppConfig.BasePathForImages);
                    var filepath    = Server.MapPath(defaultPath);
                    var filename    = string.Format("{0}{1}", Guid.NewGuid(), Path.GetExtension(upload.Filename));
                    var fullname    = Path.Combine(filepath, filename);
                    DefaultFileService.ResaveImage(upload, fullname, (UploadFileSettings)settings);
                    file.Name = Path.Combine(defaultPath, filename);
                    file.Date = DateTime.Now;

                    Repository.Save();
                    return(new FineUploaderResult(true, new
                    {
                        Url = Url.Content(file.Name)
                    }));
                }
                catch (Exception exception)
                {
                    return(new FineUploaderResult(false, null, exception.Message));
                }
            }
            return(new FineUploaderResult(false, null, "файл не был передан"));
        }
Exemple #3
0
        public async Task <IActionResult> Upload(FineUpload upload)
        {
            if (upload != null)
            {
                try
                {
                    await upload.SaveAs(true);
                }
                catch (Exception ex)
                {
                    return(new FineUploaderResult(false, error: ex.Message));
                }

                return(new FineUploaderResult(true));
            }
            return(new FineUploaderResult(false));
        }
Exemple #4
0
        public FineUploaderResult SnimiSlikuElementa(FineUpload upload, short tipDokumenta, string postedFileName, string idElementa)
        {
            var korisnik = RuntimeDataHelpers.GetRuntimeData(Request);

            Directory.CreateDirectory(Server.MapPath("~/Content/Okruzi/"));
            var filePath = Path.Combine(Server.MapPath("~/Content/Okruzi/"), idElementa + ".jpeg");

            try
            {
                upload.SaveAs(filePath, true);
                ImageHelper.SrediSliku(filePath, 1200, 100, false);
            }
            catch (Exception ex)
            {
                return(new FineUploaderResult(false, error: ExceptionParser.Parsiraj(korisnik, ex)));
            }
            return(new FineUploaderResult(true, new { url = Url.Content("~/Content/Okruzi/" + idElementa + ".jpeg?" + Guid.NewGuid().ToString()) }));
        }
Exemple #5
0
        public FineUploaderResult UploadFile(FineUpload upload)
        {
            var destinationDir = "Content/files/uploads/";
            var uFile          = StringExtension.GenerateNewFile() + Path.GetExtension(upload.Filename);
            var filePath       = Path.Combine(Path.Combine(Server.MapPath("~"), destinationDir), uFile);

            try
            {
                ImageBuilder.Current.Build(upload.InputStream, filePath, new ResizeSettings("maxwidth=1600&crop=auto"));

                var img = new Bitmap(filePath);
            }
            catch (Exception ex)
            {
                return(new FineUploaderResult(false, error: ex.Message));
            }
            return(new FineUploaderResult(true, new { fileUrl = "/" + destinationDir + uFile }));
        }
 public FineUploaderResult CreateBrandWithImage(FineUpload upload, string BrandName)
 {
     try
     {
         Brand b = new Brand();
         b.BrandName  = BrandName;
         b.BrandImage = upload.Filename;
         db.Brands.Add(b);
         db.SaveChanges();
         var dir      = Server.MapPath("../Content/brandImages/" + b.BrandId + "/");
         var filePath = Path.Combine(dir, upload.Filename);
         upload.SaveAs(filePath);
         return(new FineUploaderResult(true, new { FilePath = filePath }));
     }
     catch (Exception ex)
     {
         return(new FineUploaderResult(false, error: ex.Message));
     }
 }
 public FineUploaderResult CreateProductImages(FineUpload upload, int ProductId)
 {
     try
     {
         ProductImage p = new ProductImage();
         p.ProductId = ProductId;
         p.Image     = upload.Filename;
         db.ProductImages.Add(p);
         db.SaveChanges();
         var dir      = Server.MapPath("../Content/ProductImages/" + p.ProductId + "/");
         var filePath = Path.Combine(dir, upload.Filename);
         upload.SaveAs(filePath);
         return(new FineUploaderResult(true, new { FilePath = filePath }));
     }
     catch (Exception ex)
     {
         return(new FineUploaderResult(false, error: ex.Message));
     }
 }
Exemple #8
0
        public FineUploaderResult PostUploadFile(FineUpload upload)
        {
            // asp.net mvc will set extraParam1 and extraParam2 from the params object passed by Fine-Uploader

            var dir      = @"c:\temp";
            var filePath = Path.Combine(dir, upload.Filename);

            try
            {
                upload.SaveAs(filePath);
            }
            catch (Exception ex)
            {
                return(new FineUploaderResult(false, error: ex.Message));
            }

            // the anonymous object in the result below will be convert to json and set back to the browser
            return(new FineUploaderResult(true, new { extraInformation = 12345 }));
        }
Exemple #9
0
        public FineUploaderResult UploadFile(FineUpload UploadedFile, Guid?EntityID, int?EntityType)
        {
            // 1) Save file to server
            //		save to the folder of the provided ID value
            //		return server path
            string             relativeFilePath = string.Empty;
            FineUploaderResult uploadResult     = SaveUploadedFile(UploadedFile, EntityID, EntityType, out relativeFilePath);

            // 2) Save file to database
            //		return
            Entity_FileViewModel File = new Entity_FileViewModel();

            switch (EntityType)
            {
            case 1:
                File.PersonID = EntityID;
                break;

            case 2:
                File.BusinessID = EntityID;
                break;

            case 3:
                File.DogID = EntityID;
                break;
            }
            File.ServerPath  = relativeFilePath;
            File.DateCreated = new DateTimeOffset(DateTime.Now, TimeSpan.FromHours(-6));
            File.ContentType = UploadedFile.ContentType;

            var context = new Model.AnimalRescueEntities();

            File.ID = context.Entity_FileCreate(File).ID;

            // 3) Return file ID and Server Path to client
            return(new FineUploaderResult(true, new
            {
                FileName = File.FileName,
                FileID = File.ID.ToString(),
                FilePath = File.ServerPath
            }));
        }
Exemple #10
0
        public FineUploaderResult UploadFile(FineUpload upload)
        {
            var    dir       = Server.MapPath("~/Upload");
            int    pos1      = upload.Filename.LastIndexOf("\\");
            string fileName  = pos1 == -1 ? upload.Filename : upload.Filename.Substring(pos1 + 1, upload.Filename.Length - pos1 - 1);
            string storeName = Guid.NewGuid() + fileName;
            var    filePath  = Path.Combine(dir, storeName);

            try
            {
                upload.SaveAs(filePath);
                ViewBag.SourcePath = filePath;
            }
            catch (Exception ex)
            {
                return(new FineUploaderResult(false, error: ex.Message));
            }
            // the anonymous object in the result below will be convert to json and set back to the browser
            return(new FineUploaderResult(true, new { extraInformation = filePath }));
        }
Exemple #11
0
        public async Task <IHttpActionResult> Upload(FineUpload upload)
        {
            string uploadedTemp     = HttpContext.Current.Server.MapPath("~/App_Data/" + "TEMP/");
            string uploadedLocation = HttpContext.Current.Server.MapPath("~/App_Data/");
            string filePath         = System.IO.Path.Combine(uploadedTemp, upload.Uuid + "." + upload.Part.ToString().PadLeft(3, '0') + ".tmp");

            if (!System.IO.File.Exists(filePath))
            {
                using (System.IO.FileStream fileStream = System.IO.File.OpenWrite(filePath))
                {
                    upload.FileStream.CopyTo(fileStream);
                }
            }

            if (upload.Part == upload.TotalParts - 1) // all chunks have arrived
            {
                mergeTempFiles(uploadedTemp, upload.Uuid, uploadedLocation, upload.Filename);
            }
            return(Ok(new { success = true }));
        }
Exemple #12
0
        public ActionResult UploadFiles(FineUpload fineUpload)
        {
            var fileName = fineUpload.Filename;
            var folder   = Request.Form["folder"];

            if (string.IsNullOrEmpty(folder))
            {
                folder = "UploadFiles";
            }

            if (mediaService.FileExists(folder + "\\" + fileName))
            {
                fileName = mediaService.GetUniqueFilename(folder, fileName);
            }

            var mediaUrl = mediaService.UploadMediaFile(folder, fileName, fineUpload.InputStream);
            var newUuid  = Helper.EncodePath(Path.Combine(folder, fileName));
            var result   = new { mediaUrl, newUuid };

            return(new FineUploaderResult(true, result));
        }
 public FineUploaderResult UpdateFeatureImage(FineUpload upload, int ProductId)
 {
     try
     {
         Product p = db.Products.SingleOrDefault(x => x.ProductId == ProductId);
         var     currentFileName = p.ProductFeatureImage;
         p.ProductFeatureImage = upload.Filename;
         db.Entry(p).State     = EntityState.Modified;
         db.SaveChanges();
         var dir      = Server.MapPath("../Content/ProductImages/" + p.ProductId + "/");
         var filePath = Path.Combine(dir, upload.Filename);
         upload.SaveAs(filePath);
         var currentFilePath = Path.Combine(dir, currentFileName);
         System.IO.File.Delete(currentFilePath);
         return(new FineUploaderResult(true, new { FilePath = filePath }));
     }
     catch (Exception ex)
     {
         return(new FineUploaderResult(false, error: ex.Message));
     }
 }
 public FineUploaderResult UpdateBrandWithImage(FineUpload upload, int BrandId, string BrandName)
 {
     try
     {
         Brand b = db.Brands.FirstOrDefault(x => x.BrandId == BrandId);
         var   currentFileName = b.BrandImage;
         b.BrandName  = BrandName;
         b.BrandImage = upload.Filename;
         db.SaveChanges();
         var dir      = Server.MapPath("../Content/brandImages/" + b.BrandId + "/");
         var filePath = Path.Combine(dir, upload.Filename);
         upload.SaveAs(filePath);
         var currentFilePath = Path.Combine(dir, currentFileName);
         System.IO.File.Delete(currentFilePath);
         return(new FineUploaderResult(true, new { FilePath = filePath }));
     }
     catch (Exception ex)
     {
         return(new FineUploaderResult(false, error: ex.Message));
     }
 }
Exemple #15
0
        public FineUploaderResult UploadDokumenta(FineUpload upload, long idPredmeta)
        {
            var             korisnik = RuntimeDataHelpers.GetRuntimeData(Request);
            PodaciDokumenta fajl;

            try
            {
                Directory.CreateDirectory(Server.MapPath("~/App_Data/"));
                var    replacedFileName = upload.Filename.Replace("&", "_");
                string filePath         = Path.Combine(Server.MapPath("~/App_Data/"), replacedFileName);

                upload.SaveAs(filePath);
                fajl = DMSData.SnimiDokumentPredmeta(korisnik, idPredmeta, upload.Filename, filePath);
            }
            catch (Exception ex)
            {
                return(new FineUploaderResult(false, error: ExceptionParser.Parsiraj(korisnik, ex)));
            }

            return(new FineUploaderResult(true, new { file = fajl }));
        }
Exemple #16
0
 public virtual ActionResult UploadImage(FineUpload file)
 {
     if (file != null && file.InputStream != null && file.InputStream.Length > 0)
     {
         var fileService = DependencyResolver.Current.GetService <IFileService>();
         var item        = new WebFile {
             Date = DateTime.Now
         };
         fileService.SaveFile(file.InputStream, new UploadFileSettings {
             PathToSave = WebConfig.BasePathForImages
         }, item, file.Filename);
         Repository.DataContext.Set <WebFile>().Add(item);
         Repository.Save();
         return(Json(new
         {
             success = true,
             id = item.Id,
             url = Url.Content(item.Url)
         }));
     }
     return(Json(new { success = false, error = "файл не был загружен" }));
 }
Exemple #17
0
        private FineUploaderResult SaveUploadedFile(FineUpload upload, Guid?EntityID, int?EntityType, out string relativeFilePath)
        {
            string entityType = string.Empty;

            switch (EntityType)
            {
            case 1:
                entityType = "Person";
                break;

            case 2:
                entityType = "Org";
                break;

            case 3:
                entityType = "Dog";
                break;
            }

            string folder       = Path.Combine("~/Upload", entityType, EntityID.Value.ToString(), "Files");
            string directory    = Server.MapPath(folder);
            var    fullFilePath = Path.Combine(directory, HttpContext.Server.UrlDecode(upload.Filename));

            relativeFilePath = Path.Combine(folder, HttpContext.Server.UrlDecode(upload.Filename));

            FineUploaderResult uploadResult = new FineUploaderResult(true);

            try
            {
                upload.SaveAs(fullFilePath);
            }
            catch (Exception ex)
            {
                uploadResult = new FineUploaderResult(false, error: ex.Message);
            }
            return(uploadResult);
        }
        public ActionResult ProcessUpload(FineUpload upload)
        {
            string saveUrl     = "/Uploads/";
            string dirPath     = _environment.WebRootPath + saveUrl;
            string fileExt     = Path.GetExtension(upload.Filename).ToLower();
            string newFileName = Guid.NewGuid().ToString("N") + fileExt;

            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            var filePath = Path.Combine(dirPath, newFileName);

            try
            {
                upload.SaveAs(filePath);
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, Url = "/Uploads/" + newFileName, isUploaded = false, message = "上传失败" }));
            }

            return(Json(new { success = true, Url = "/Uploads/" + newFileName, isUploaded = true, message = "上传成功" }));
        }
Exemple #19
0
        public static void ResaveImage(FineUpload upload, string filename, UploadFileSettings settings = null)
        {
            // в некоторые типы картинок можно запихать код для исполнения, чтобы пресечь это, необходимо пересохранить кратинку
            using (var img = Image.FromStream(upload.InputStream))
            {
                // подготовка картинки к сохраниению, рисуем ватермарки и тыды
                if (settings != null && settings.IsImage)
                {
                    if (settings.Watermarks.Any(watermarkSettings => watermarkSettings.FillType != WatermarkFillType.None))
                    {
                        using (var g = Graphics.FromImage(img))
                        {
                            foreach (var wm in settings.Watermarks)
                            {
                                using (var wmImage = Image.FromFile(HttpContext.Current.Server.MapPath(wm.RelativePath)))
                                {
                                    var k = 1.0;
                                    if ((wm.ReduceWidth.HasValue && img.Width <= wm.ReduceWidth.Value) || (wm.ReduceHeight.HasValue && img.Height <= wm.ReduceHeight.Value))
                                    {
                                        k = wm.ReduceFactor;
                                    }
                                    var width  = wmImage.Width / k;
                                    var height = wmImage.Height / k;
                                    if (wm.FillType == WatermarkFillType.Mosaic)
                                    {
                                        var cY = 0;
                                        while (cY < img.Height)
                                        {
                                            var cX = 0;
                                            while (cX < img.Width)
                                            {
                                                g.DrawImage(wmImage, new Rectangle(cX, cY, (int)width, (int)height));
                                                cX += wmImage.Width;
                                            }
                                            cY += wmImage.Height;
                                        }
                                    }
                                    else
                                    {
                                        // координаты на исходном изображении куда выводить ватермарк
                                        var left = 0.0;
                                        var top  = 0.0;
                                        switch (wm.FillType)
                                        {
                                        case WatermarkFillType.TopLeft:
                                            left = wm.Margins.Left / k;
                                            top  = wm.Margins.Top / k;
                                            break;

                                        case WatermarkFillType.TopRight:
                                            left = img.Width - wm.Margins.Right / k - width;
                                            top  = wm.Margins.Top / k;
                                            break;

                                        case WatermarkFillType.BottomLeft:
                                            left = wm.Margins.Left / k;
                                            top  = img.Height - wm.Margins.Bottom / k - height;
                                            break;

                                        case WatermarkFillType.BottomRight:
                                            left = img.Width - wm.Margins.Right / k - width;
                                            top  = img.Height - wm.Margins.Bottom / k - height;
                                            break;

                                        case WatermarkFillType.Center:
                                            left = (img.Width - width) / 2;
                                            top  = (img.Height - height) / 2;
                                            break;

                                        case WatermarkFillType.Stretch:
                                            left   = wm.Margins.Left / k;
                                            top    = wm.Margins.Top / k;
                                            width  = img.Width - wm.Margins.Right / k;
                                            height = img.Height - wm.Margins.Bottom / k;
                                            break;

                                        case WatermarkFillType.Custom:
                                            left   = wm.Left + wm.Margins.Left;
                                            top    = wm.Top + wm.Margins.Top;
                                            width  = wm.Width == 0 ? wmImage.Width : wm.Width;
                                            height = wm.Height == 0 ? wmImage.Height : wm.Height;
                                            break;

                                        default:
                                            throw new ArgumentOutOfRangeException();
                                        }
                                        g.DrawImage(wmImage, new Rectangle((int)left, (int)top, (int)width, (int)height));
                                    }
                                }
                            }
                        }
                    }
                }
                SaveByExt(img, filename);
            }
        }
Exemple #20
0
        public FineUploaderResult UploadFile(FineUpload upload, ImageUploadViewModel model, FormCollection form)
        {
            int counter = 1;

            //   var hardPath = Server.MapPath("~/").Replace("httpdocs\\Presentation\\Nop.Web\\", "uploaded_image_libraries\\");

            var hardPath = Path.Combine(Server.MapPath("~/App_Data/"), ImageLibrary);

            if (!Directory.Exists(hardPath))
            {
                try
                {
                    Directory.CreateDirectory(hardPath);
                }
                catch (Exception)
                {
                    throw new Exception("Cannot Create BaseLine Config.");
                }
            }

            var currentShow = Path.Combine(hardPath, CurrentShow);

            // var dir = @"c:\upload\path";
            // var filePath = Path.Combine(dir, upload.Filename);

            if (!Directory.Exists(currentShow))
            {
                try
                {
                    Directory.CreateDirectory(currentShow);
                }
                catch (Exception)
                {
                    throw new Exception("Cannot Create BaseLine Show File");
                }
            }

            var uploadFileName = Path.GetFileName(upload.Filename);

            if (uploadFileName == null)
            {
                return(new FineUploaderResult(false, error: "BadInput"));
            }

            var owner       = model.EmailAddress.Replace("@", ".");
            var xmlFileName = model.ArtTitle + ".xml";

            //  var dir = Server.MapPath(currentShow) + owner;
            // var dir = OffsetFromBase + owner;

            var dir = currentShow + "\\" + owner;


            var filePath = Path.Combine(dir, uploadFileName);
            var infoPath = Path.Combine(dir, xmlFileName);

            string xmlFile = BuildXmlFile(model, filePath);


            if (Directory.Exists(dir))
            {
                var directoryFiles = Directory.GetFiles(dir);

                counter += directoryFiles.Count(path => Path.GetExtension(path).ToLower() == ".xml");
            }

            if (counter <= MaxCount)
            {
                try
                {
                    if (System.IO.File.Exists(filePath))
                    {
                        throw new Exception("This image previously submitted!");
                    }

                    upload.SaveAs(filePath);
                }
                catch (Exception ex)
                {
                    return(new FineUploaderResult(false, error: ex.Message));
                }

                try
                {
                    if (System.IO.File.Exists(infoPath))
                    {
                        throw new Exception("This image previously submitted!");
                    }

                    System.IO.File.WriteAllText(infoPath, xmlFile);
                }
                catch (Exception ex)
                {
                    // remove uploaded file
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }

                    return(new FineUploaderResult(false, error: ex.Message));
                }


                model.ModelState = "Uploaded";
            }
            //   var jresult = (counter >= MaxCount) ? "Limit Reached, Pay Fee Below" : "Submit New Entry or Pay Fee Below";

            var jresult = (counter >= MaxCount)? "Limit Reached - Submitted Count: " + counter : "Submit New Entry - Submitted Count: " + counter;

            // the anonymous object in the result below will be convert to json and set back to the browser
            // return values  bool success, object otherData = null, string error = null, bool? preventRetry = null

            return(new FineUploaderResult(true, new { extraInformation = jresult }));
        }
Exemple #21
0
        public virtual FineUploaderResult UploadFile(FineUpload upload, int id, string propName)
        {
            var settings = GetFileSettings(propName);

            if (upload.InputStream != null && upload.InputStream.Length != 0 && settings != null)
            {
                try
                {
                    var entity = Repository.GetByPrimaryKey(id);
                    var value  = TypeHelpers.GetPropertyValue(entity, propName);

                    Func <IFileEntity> saveImage = () =>
                    {
                        // надо создать новое value и добавить его в базу
                        var t    = TypeHelpers.GetPropertyType(entity, propName);
                        var file = (IFileEntity)Activator.CreateInstance(t);

                        // формируем пути
                        var defaultPath = AppConfig.GetValue(AppConfig.BasePathForImages);
                        if (String.IsNullOrEmpty(defaultPath))
                        {
                            defaultPath = "~/Content/";
                        }
                        var relativePath = settings.PathToSave ?? defaultPath;
                        if (string.IsNullOrEmpty(relativePath))
                        {
                            throw new Exception("Не указан путь сохранения файла");
                        }
                        var path     = Server.MapPath(relativePath);
                        var filename = string.Format("{0}{1}", Guid.NewGuid(), Path.GetExtension(upload.Filename));
                        var fullname = Path.Combine(path, filename);

                        // сохраняем файл
                        if (settings.IsImage)
                        {
                            DefaultFileService.ResaveImage(upload, fullname, settings);
                        }
                        else
                        {
                            upload.SaveAs(fullname);
                        }

                        file.Name       = Path.Combine(relativePath, filename);
                        file.SourceName = upload.Filename;
                        file.Date       = DateTime.Now;
                        file.Visibility = true;
                        file.Size       = new FileInfo(fullname).Length;
                        var entitySetName = TypeHelpers.GetEntitySetName(file, Repository.DataContext);
                        ((IObjectContextAdapter)Repository.DataContext).ObjectContext.AddObject(entitySetName, file);
                        return(file);
                    };

                    IFileEntity result;
                    if (value is IEnumerable)
                    {
                        result = saveImage();
                        var        type            = value.GetType();
                        MethodInfo methodInfo      = type.GetMethod("Add");
                        object[]   parametersArray = new object[] { result };
                        methodInfo.Invoke(value, parametersArray);
                        // aganzha
                        //var set = (System.Collections.Generic.HashSet<object>)value;


                        //var type = result.GetType();
                        //var list = ((IListSource)value).GetList();
                        //var sortList = list.Cast<IFileEntity>().ToList();
                        //if (sortList.Any())
                        //{
                        //    result.Sort = sortList.Max(fileEntity => fileEntity.Sort) + 1;
                        //}
                        //list.Add(result);
                    }
                    else
                    {
                        result = (IFileEntity)value;
                        if (result != null)
                        {
                            DefaultFileService.DeleteFile(result, ControllerContext.HttpContext);
                            ((IObjectContextAdapter)Repository.DataContext).ObjectContext.DeleteObject(result);
                        }
                        result = saveImage();
                        TypeHelpers.SetPropertyValue(entity, propName, result);
                    }
                    Repository.Save();
                    return(new FineUploaderResult(true, new
                    {
                        result.Id,
                        Url = Url.Content(result.Name),
                        result.Alt,
                        result.Title,
                        result.Description,
                        result.Visibility,
                        result.SourceName
                    }));
                }
                catch (Exception exception)
                {
                    return(new FineUploaderResult(false, null, exception.Message));
                }
            }
            return(new FineUploaderResult(false, null, "файл не был передан"));
        }