Beispiel #1
0
        public static List <Photo> CopyAdPhotos(List <Photo> photos, int adId)
        {
            if (!photos.Any())
            {
                return(new List <Photo>());
            }
            foreach (var group in photos.GroupBy(p => p.GroupId).Select(g => g.ToList()).ToList())
            {
                var groupId = Guid.NewGuid();
                foreach (var photo in group)
                {
                    var oldFullPath = photo.FullPath.Replace("/", "\\");
                    if (!System.IO.File.Exists(oldFullPath))
                    {
                        continue;
                    }
                    photo.AdId = adId;
                    var directory = PhotosController.GetFileDirectoryForPhotos(photo);
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }
                    photo.GroupId = groupId;
                    string fileName = String.Empty;
                    #region Get unique fileName
                    while (true)
                    {
                        string _fileName = Guid.NewGuid().ToString().Replace("-", "").Remove(10) + ".jpg";
                        if (!System.IO.File.Exists(directory + _fileName))
                        {
                            fileName = _fileName;
                            break;
                        }
                    }

                    if (fileName == String.Empty)
                    {
                        LogsDAL.AddError("in PhotosController.SavePhoto(): filePathAndName = String.Empty");
                        //return false;
                    }
                    #endregion
                    photo.FileNameWithExtension = fileName;
                    System.IO.File.Copy(oldFullPath, photo.FullPath.Replace("/", "\\"));
                    photo.Added   = DateTime.Now.ToUniversalTime();
                    photo.Changed = photo.Added;
                    PhotosDAL.AddPhoto(photo);
                }
            }
            return(photos);
        }
Beispiel #2
0
        public static bool DeletePhoto(Photo photo)
        {
            var group = PhotosDAL.GetPhotoGroup(photo.GroupId);

            foreach (var photoToRemove in group)
            {
                if (System.IO.File.Exists(photoToRemove.FullPath))
                {
                    System.IO.File.Delete(photoToRemove.FullPath);
                }
                else
                {
                    LogsDAL.AddError("in PhotosController.DeletePhoto(): System.IO.File.Exists(photo.FullPath) == false");
                    return(false);
                }
            }
            PhotosDAL.DeletePhotoGroup(photo.GroupId);
            return(true);
        }
Beispiel #3
0
        public static Photo SavePhoto(System.Drawing.Image photoImage, Photo photo)
        {
            var directory = GetFileDirectoryForPhotos(photo);

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

            /*Photo photo = new Photo();
             * photo.UserId = userId;
             * //photo.ImageType = "jpeg";
             * //photo.ModerateResult = moderateResult;
             * //photo.IsMain = setMain;
             * //photo.Width = photo.Width;
             * //photo.Height = photo.Height;
             * //photo.NearestWidth = nearestWidth;*/
            #region Get unique fileName
            string fileName = String.Empty;
            while (true)
            {
                string _fileName = Guid.NewGuid().ToString().Replace("-", "").Remove(10) + ".jpg";
                if (!System.IO.File.Exists(directory + _fileName))
                {
                    fileName = _fileName;
                    break;
                }
            }

            if (fileName == String.Empty)
            {
                LogsDAL.AddError("in PhotosController.SavePhoto(): filePathAndName = String.Empty");
                //return false;
            }
            #endregion
            SaveJPGWithCompressionSetting(photoImage, directory + fileName, 70L);
            photo.FileNameWithExtension = fileName;
            photo.Width  = photoImage.Width;
            photo.Height = photoImage.Height;
            photo.Id     = PhotosDAL.AddPhoto(photo);
            return(photo);
        }
Beispiel #4
0
        public static List <Photo> AddPhoto(System.Drawing.Image inputImage, Photo photo)
        {
            var    result = new List <Photo>();
            string fileDirectoryForPhotos = GetFileDirectoryForPhotos(photo);

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

            photo.GroupId = Guid.NewGuid();

            try
            {
                result.Add(ResizeAndSavePhotoAndPhotoInfo(inputImage, 200, 200, photo));
                result.Add(SavePhoto(inputImage, photo));
            }
            catch (Exception ex)
            {
                LogsDAL.AddError("in PhotosController.AddPhotoAndGenerateResizedPhotos(): " + ex.ToString());
            }
            return(result);
        }
Beispiel #5
0
        public static string UploadPhoto(HttpRequestBase Request, int userId, int?adId = null)
        {
            var result = "";

            if (SM.CurrentUserIsNull)
            {
                return("Для загрузки файлов необходимо авторизоваться на сайте");
            }
            foreach (string upload in Request.Files)
            {
                var uploadFile = Request.Files[upload];
                if (uploadFile == null || uploadFile.ContentLength == 0)
                {
                    continue;
                }

                string filename  = uploadFile.FileName;
                var    extension = Path.GetExtension(filename);
                if (extension != null)
                {
                    extension = extension.Replace(".", "");
                }

                var deniedExtensions = new List <string>()
                {
                    "exe", "js"
                };
                if (deniedExtensions.Contains(extension))
                {
                    return("Запрещено загружать файлы с расширением " + extension);
                }

                var isImage = new List <string>()
                {
                    "jpg", "jpeg", "png"
                }.Contains(extension);
                #region обработка изображения
                //var resizedPhoto = PhotosController.GetResizedPhoto(uploadFile.InputStream, 130, 130);

                Image inputImage = new Bitmap(uploadFile.InputStream);
                var   photo      = new Photo()
                {
                    UserId         = userId,
                    AdId           = adId,
                    IsMain         = false,
                    ModerateResult = ModerateResults.NotChecked,
                    Added          = DateTime.Now.ToUniversalTime(),
                    Changed        = DateTime.Now.ToUniversalTime(),
                    Width          = inputImage.Width,
                    Height         = inputImage.Height,
                    PhotoType      = (adId != null ? PhotoTypes.AdPhoto : PhotoTypes.CompanyLogo)
                };

                var folder = PhotosController.GetFileDirectoryForPhotos(photo);
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                try
                {
                    //uploadFile.SaveAs(photo.FullPath);
                    var photos = PhotosController.AddPhoto(inputImage, photo);
                    if (photos.Any())
                    {
                        result += "ok," + photos.FirstOrDefault().Id + "," + photo.Url + "|";
                    }
                }
                catch (Exception ex)
                {
                    result = "error";
                    LogsDAL.AddError("in UserController.UploadPhoto(): userId = " + photo.UserId + ", exception: " + ex);
                    return(result);
                }
                #endregion

                /*if (falseisImage)
                 * {
                 #region обработка изображения
                 *  var resizedPhoto = PhotosController.GetResizedPhoto(uploadFile.InputStream, 130, 130);
                 *
                 *  var fileName = "main-" + Guid.NewGuid() + extension;
                 *
                 *  var photo = new Photo()
                 *  {
                 *      UserId = SM.CurrentUserId,
                 *      FileNameWithExtension = fileName,
                 *      IsMain = true,
                 *      ModerateResult = ModerateResults.NotChecked,
                 *      Added = DateTime.Now,
                 *      Changed = DateTime.Now,
                 *      Width = resizedPhoto.Width,
                 *      Height = resizedPhoto.Height
                 *  };
                 *
                 *  bool result = true;
                 *  try
                 *  {
                 *      //uploadFile.SaveAs(photo.FullPath);
                 *      resizedPhoto.Save(photo.FullPath);
                 *  }
                 *  catch (Exception ex)
                 *  {
                 *      result = false;
                 *      LogsDAL.AddError("in UserController.UploadPhoto(): userId = " + photo.UserId + ", exception: " + ex);
                 *  }
                 #endregion
                 * }
                 * else
                 * {
                 *  var newFileFullPath = folder + "/" + filename;
                 *  if (System.IO.File.Exists(newFileFullPath))
                 *      return "На сервере уже есть файл с таким названием. Пожалуйста, переименуйте файл и попробуйте снова";
                 *
                 *  uploadFile.SaveAs(folder + "/" + filename);
                 *
                 *  var file = new MyFile()
                 *  {
                 *      NameWithExtension = filename,
                 *      Extension = extension,
                 *      ContainingFolderPath = folder,
                 *      IsAttachToComment = true,
                 *      UploadedUserId = SM.CurrentUserId,
                 *      UploadedDate = DateTime.Now,
                 *      SizeKb = uploadFile.ContentLength / 1000
                 *  };
                 *
                 *  var newFileId = FilesDAL.AddFile(file);
                 *
                 *  return "ok," + newFileId + "," + filename;
                 * }*/
            }

            return(result);
        }
        public string UploadFiles(int respondentId)
        {
            var result = "";

            if (Request == null || Request.Files == null || Request.Files.Count == 0)
            {
                return("Не выбрано ни одного файла");
            }

            if (SM.CurrentUserIsNull)
            {
                return("Для загрузки файлов необходимо авторизоваться на сайте");
            }

            var files  = new List <UserFile>();
            var userId = SM.CurrentUserId;

            var message = new Message
            {
                SenderId    = userId,
                RecipientId = respondentId,
                Text        = "Прикрепленные файлы:",
                Files       = new List <UserFile>()
            };
            var messageId = UserHelper.AddMessage(message);

            message.Id = messageId;

            foreach (string upload in Request.Files)
            {
                var uploadFile = Request.Files[upload];
                if (uploadFile == null || uploadFile.ContentLength == 0)
                {
                    continue;
                }

                var byteCount = uploadFile.ContentLength;
                if (byteCount > 50 * 1024 * 1024)
                {
                    result += "error,0,0";
                    continue;
                }

                string filename  = uploadFile.FileName;
                var    extension = Path.GetExtension(filename);
                if (extension != null)
                {
                    extension = extension.Replace(".", "");
                    filename  = filename.Substring(0, filename.IndexOf(extension) - 1);
                }

                var deniedExtensions = new List <string>()
                {
                    "exe", "js"
                };
                if (deniedExtensions.Contains(extension))
                {
                    return("Запрещено загружать файлы с расширением " + extension);
                }

                //var isImage = new List<string>() { "jpg", "jpeg", "png" }.Contains(extension);

                var file = new UserFile()
                {
                    UserId         = userId,
                    MessageId      = 0,
                    Name           = filename,
                    Extension      = extension,
                    ModerateResult = ModerateResults.NotChecked,
                    Added          = DateTime.Now.ToUniversalTime(),
                    Changed        = DateTime.Now.ToUniversalTime()
                };
                message.Files.Add(file);
                file.MessageId = messageId;

                try
                {
                    var folder = GetFileDirectoryForFiles(file);
                    if (!Directory.Exists(folder))
                    {
                        Directory.CreateDirectory(folder);
                    }
                    uploadFile.SaveAs(file.FullPath);
                    files.Add(file);
                    result += $"ok,{file.NameWithExtension},{file.Url}|";
                }
                catch (Exception ex)
                {
                    result = "error";
                    LogsDAL.AddError("in UserController.UploadFile(): userId = " + file.UserId + ", exception: " + ex);
                    return(result);
                }
            }

            SM.AddMessageToCurrentDialogs(message);

            FilesDAL.AddFiles(files);

            return(result);
        }