Exemplo n.º 1
0
        public MediaFile AddFile(Stream stream, string fileName, string contentType, long contentLength,
                                 MediaCategory mediaCategory = null)
        {
            fileName = Path.GetFileName(fileName);

            fileName = fileName.GetTidyFileName();

            var mediaFile = new MediaFile
            {
                FileName      = fileName,
                ContentType   = contentType,
                ContentLength = contentLength,
                FileExtension = Path.GetExtension(fileName),
            };

            if (mediaCategory != null)
            {
                mediaFile.MediaCategory = mediaCategory;
                int?max =
                    _session.Query <MediaFile>()
                    .Where(x => x.MediaCategory.Id == mediaFile.MediaCategory.Id)
                    .Max(x => (int?)x.DisplayOrder);
                mediaFile.DisplayOrder = (max.HasValue ? (int)max + 1 : 1);
            }

            if (mediaFile.IsImage())
            {
                _imageProcessor.EnforceMaxSize(ref stream, mediaFile, _mediaSettings);
                _imageProcessor.SetFileDimensions(mediaFile, stream);
            }

            string fileLocation = GetFileLocation(fileName, mediaCategory);

            mediaFile.FileUrl = _fileSystem.SaveFile(stream, fileLocation, contentType);


            _session.Transact(session =>
            {
                session.Save(mediaFile);
                if (mediaCategory != null)
                {
                    mediaCategory.Files.Add(mediaFile);
                    session.SaveOrUpdate(mediaCategory);
                }
            });

            stream.Dispose();
            return(mediaFile);
        }