예제 #1
0
        private void SaveFilesHelper()
        {
            string basePath  = @"C:\Users\User\Desktop\beta";
            string finalPath = settings.BasePath.Replace("dev", "beta");

            if (!_storageProvider.IsFolderExits(finalPath))
            {
                _storageProvider.TryCreateFolder(finalPath);
            }

            List <string> files = DirSearch(basePath);

            foreach (var file in files)
            {
                Image image  = Image.FromFile(Path.Combine(file), true);
                var   format = image.RawFormat;
                using (var ms = new MemoryStream())
                {
                    image.Save(ms, format);
                    var newPath = file.Replace(@"C:\Users\User\Desktop\beta\userFiles\", "");
                    if (_storageProvider.IsFileExists(Path.Combine(finalPath, newPath)))
                    {
                        _storageProvider.DeleteFile(Path.Combine(finalPath, newPath));
                    }
                    _storageProvider.CreateFile(Path.Combine(finalPath, newPath), ms.ToArray());
                }
            }
        }
예제 #2
0
        public void CreateFileAndDeleteFileTakesAnySlash()
        {
            Assert.That(_storageProvider.ListFiles(@"Subfolder1").Count(), Is.EqualTo(2));
            var alpha = _storageProvider.CreateFile(@"SubFolder1/alpha.txt");
            var beta  = _storageProvider.CreateFile(@"SubFolder1\beta.txt");

            Assert.That(_storageProvider.ListFiles(@"Subfolder1").Count(), Is.EqualTo(4));
            Assert.That(alpha.GetPath(), Is.EqualTo(Path.Combine("SubFolder1", "alpha.txt")));
            Assert.That(beta.GetPath(), Is.EqualTo(Path.Combine("SubFolder1", "beta.txt")));
            _storageProvider.DeleteFile(@"SubFolder1\alpha.txt");
            _storageProvider.DeleteFile(@"SubFolder1/beta.txt");
            Assert.That(_storageProvider.ListFiles(@"Subfolder1").Count(), Is.EqualTo(2));
        }
예제 #3
0
        public MigrateMediaResult MigratAzureBlobStorageToFileSystem(string connectionString, bool isOverwrite)
        {
            var mediaItems = _mediaLibraryService.GetMediaContentItems()
                             .List();

            var result          = new MigrateMediaResult();
            var azureFileSystem = InitializeAzureFileSystem(connectionString);

            foreach (var mediaItem in mediaItems)
            {
                var path = Path.Combine(mediaItem.FolderPath, mediaItem.FileName);

                if (!azureFileSystem.FileExists(path) || (!isOverwrite && _storageProvider.FileExists(path)))
                {
                    result.IgnoredCount++;
                    continue;
                }

                try
                {
                    if (isOverwrite && _storageProvider.FileExists(path))
                    {
                        _storageProvider.DeleteFile(path);
                    }

                    var file      = _storageProvider.CreateFile(path);
                    var azureFile = azureFileSystem.GetFile(path);

                    using (var inputStream = azureFile.OpenRead())
                    {
                        using (var outputStream = file.OpenWrite())
                        {
                            var buffer = new byte[8192];
                            while (true)
                            {
                                var length = inputStream.Read(buffer, 0, buffer.Length);

                                if (length <= 0)
                                {
                                    break;
                                }

                                outputStream.Write(buffer, 0, length);
                            }
                        }
                    }

                    result.SuccessfulTransferCount++;
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, string.Format("Failed to transfer media {0}.", path));
                    result.UnsuccessfulTransferCount++;

                    _storageProvider.DeleteFile(path);
                }
            }

            return(result);
        }
예제 #4
0
        static void TestProvider(IStorageProvider provider, string nameProvider)
        {
            byte[]     buff     = new byte[0];
            var        fileName = pathToTestFile;
            FileStream fs       = new FileStream(fileName,
                                                 FileMode.Open,
                                                 FileAccess.Read);
            BinaryReader br       = new BinaryReader(fs);
            long         numBytes = new FileInfo(fileName).Length;

            buff = br.ReadBytes((int)numBytes);

            var          path        = "testfolder\\test.jpeg";
            var          file        = provider.CreateFile(path);
            var          streamWrite = file.OpenWrite();
            BinaryWriter bw          = new BinaryWriter(streamWrite);

            bw.Write(buff);
            Console.WriteLine("********* " + nameProvider + " ****************");
            Console.WriteLine("Create file");
            if (provider.IsFileExists(path))
            {
                Console.WriteLine("File exist");
            }
            else
            {
                Console.WriteLine("File not exist");
            }
            provider.DeleteFile(path);
            Console.WriteLine("Delete file");
        }
예제 #5
0
        public void Save(int hashCode, CombinatorResource resource)
        {
            var scliceCount = _fileRepository.Count(file => file.HashCode == hashCode);

            var fileRecord = new CombinedFileRecord()
            {
                HashCode       = hashCode,
                Slice          = ++scliceCount,
                Type           = resource.Type,
                LastUpdatedUtc = _clock.UtcNow,
                Settings       = _combinatorResourceManager.SerializeResourceSettings(resource)
            };

            if (!String.IsNullOrEmpty(resource.Content))
            {
                var path = MakePath(fileRecord);

                using (var stream = _storageProvider.CreateFile(path).OpenWrite())
                {
                    var bytes = Encoding.UTF8.GetBytes(resource.Content);
                    stream.Write(bytes, 0, bytes.Length);
                }
            }

            _fileRepository.Create(fileRecord);
        }
        public static IStorageFile OpenOrCreate(this IStorageProvider storageProvider, string path)
        {
            if (!storageProvider.FileExists(path))
            {
                return(storageProvider.CreateFile(path));
            }

            return(storageProvider.GetFile(path));
        }
예제 #7
0
        public void SaveSnapshot(Uri uri)
        {
            var urlString = uri.ToString();

            // This folder will be created before download process will copy files into it
            var folderPath = _storageProvider.Combine("_ArchivedLinks", urlString.GetHashCode().ToString());

            var contentType = GetContentType(uri);

            var allowableFileContentTypes = new string[] { "application/pdf", "image/jpeg", "image/jpg", "image/png", "image/gif" };

            if (allowableFileContentTypes.Contains(contentType))
            {
                DownloadFile(urlString, uri, folderPath, true);
            }
            else if (contentType == "text/html")
            {
                var htmlWeb  = new HtmlWeb();
                var document = htmlWeb.Load(urlString);

                DownloadHtml(ref document, uri, folderPath);
                htmlWeb.Get(urlString, "/");

                var indexPath = _storageProvider.Combine(folderPath, "index.html");
                if (_storageProvider.FileExists(indexPath))
                {
                    _storageProvider.DeleteFile(indexPath);
                }

                using (var stream = _storageProvider.CreateFile(indexPath).OpenWrite())
                {
                    document.Save(stream);
                }
            }
            else
            {
                throw new NotSupportedException("Uri type not supported");
            }
        }
예제 #8
0
        private IStorageFile GetJournalFile(string executionId)
        {
            IStorageFile journalFile;
            var          journalPath = _storageProvider.Combine(RecipeJournalFolder, executionId);

            try {
                if (_storageProvider.TryCreateFolder(RecipeJournalFolder))
                {
                    var webConfigPath = _storageProvider.Combine(RecipeJournalFolder, "web.config");
                    var webConfigFile = _storageProvider.CreateFile(webConfigPath);
                    WriteWebConfig(webConfigFile);
                }
                journalFile = _storageProvider.GetFile(journalPath);
            }
            catch (ArgumentException) {
                journalFile = _storageProvider.CreateFile(journalPath);
                var recipeStepElement = new XElement("RecipeJournal");
                recipeStepElement.Add(new XElement("Status", "Unknown"));
                WriteJournal(journalFile, recipeStepElement);
            }

            return(journalFile);
        }
        public IStorageFile CreateThumbnail(string mediaPath, string name, int width, int height, bool force = false)
        {
            if (!_mediaService.GetMediaFiles(mediaPath).Any(i => i.Name == name))
            {
                return(null);
            }

            string fileHash              = CreateMd5Hash(string.Concat(mediaPath, name, width, height));
            string fileExtension         = Path.GetExtension(name);
            string thumbnailFileName     = fileHash + fileExtension;
            string relativePath          = Combine(mediaPath, name);
            string thumbnailRelativePath = Combine(ThumbnailsCacheMediaPath, thumbnailFileName);

            if (_mediaService.GetMediaFiles(ThumbnailsCacheMediaPath).Any(i => i.Name == thumbnailFileName))
            {
                if (force)
                {
                    _mediaService.DeleteFile(ThumbnailsCacheMediaPath, thumbnailFileName);
                }
                else
                {
                    return(_storageProvider.GetFile(thumbnailRelativePath));
                }
            }

            var imageFile  = _storageProvider.GetFile(relativePath);
            var outputFile = imageFile;

            using (var imageStream = imageFile.OpenRead())
            {
                Image image = Image.FromStream(imageStream);
                if (MustBeScaledDown(image, width, height))
                {
                    var thumbnailFile = _storageProvider.CreateFile(thumbnailRelativePath);
                    using (var thumbnailStream = thumbnailFile.CreateFile())
                        ImageBuilder.Current.Build(image, thumbnailStream, new ResizeSettings()
                        {
                            Width = width, Height = height
                        });
                    outputFile = thumbnailFile;
                }
            }

            if (outputFile != imageFile)
            {
                _signals.Trigger("Contrib.Thumbnails." + fileHash + ".Changed");
            }

            return(outputFile);
        }
        public static void WriteAllText(this IStorageProvider storageProvider, string path, string contents)
        {
            if (storageProvider.FileExists(path))
            {
                storageProvider.DeleteFile(path);
            }

            var file = storageProvider.CreateFile(path);

            using (var stream = file.OpenWrite())
                using (var streamWriter = new StreamWriter(stream)) {
                    streamWriter.Write(contents);
                }
        }
 private void CreaProfilesPrivateWebConfig()
 {
     if (!_mediaPrivateFolder.IsPrivate("/Media/" + _settings.Name + "/_Profiles/Private/"))
     {
         lock (string.Intern("configdelprofile" + _settings.Name)) {
             if (!_mediaPrivateFolder.IsPrivate("/Media/" + _settings.Name + "/_Profiles/Private/"))
             {
                 var a     = _storageProvider.CreateFile("_Profiles/Private/web.config");
                 var o     = a.OpenWrite();
                 var bytes = Encoding.ASCII.GetBytes("<?xml version=\"1.0\" encoding=\"utf-8\"?><configuration><system.webServer><staticContent><clientCache cacheControlMode=\"UseMaxAge\" cacheControlMaxAge=\"7.00:00:00\" /></staticContent><handlers accessPolicy=\"Script,Read\"><remove name=\"StaticFile\"/> <!-- For any request to a file exists on disk, return it via native http module. AccessPolicy=\"Script\" above is to allow for a managed 404 page. --></handlers></system.webServer></configuration>");
                 o.Write(bytes, 0, bytes.Count());
                 o.Close();
             }
         }
     }
 }
예제 #12
0
        public void Execute(IStorageProvider storageProvider, IPackage package)
        {
            foreach (ZipArchiveEntry entry in package.Entries)
            {
                if (inputRegex.IsMatch(entry.FullName))
                {
                    string destinationPath = this.TargetPattern.Replace("$(FileName)", entry.Name);

                    using (Stream entryStream = entry.Open()) {
                        using (Stream fileStream = storageProvider.CreateFile(destinationPath)) {
                            entryStream.CopyTo(fileStream);
                        }
                    }
                }
            }
        }
예제 #13
0
        static void TestWriteEncryptionProvider(IStorageProvider provider, IStorageEncryptionProvider encryptionProvider, byte[] iv)
        {
            byte[]     buff     = new byte[0];
            var        fileName = pathToTestFile;
            FileStream fs       = new FileStream(fileName,
                                                 FileMode.Open,
                                                 FileAccess.Read);

            var path = "testfolder\\testencryption990.jpeg";

            provider.DeleteFile(path);
            var file        = provider.CreateFile(path);
            var streamWrite = file.OpenCryptoWrite(encryptionProvider, iv);

            CopyStream(fs, streamWrite);
        }
        public void Index()
        {
            var          filePath = "Demo/NotMeerkat.txt";
            IStorageFile file;

            if (!_storageProvider.FileExists(filePath))
            {
                file = _storageProvider.CreateFile(filePath);
            }
            else
            {
                file = _storageProvider.GetFile(filePath);
            }
            using (var stream = file.OpenWrite())
                using (var streamWriter = new StreamWriter(stream))
                {
                    streamWriter.Write("Hello world! " + _clock.UtcNow.ToString());
                }
        }
예제 #15
0
        public static void AnyFiles(IStorageProvider provider)
        {
            byte[] buff     = new byte[0];
            var    fileName = @"..\..\TestFile.jpeg";
            var    fs       = new FileStream(fileName,
                                             FileMode.Open,
                                             FileAccess.Read);
            var  br       = new BinaryReader(fs);
            long numBytes = new FileInfo(fileName).Length;

            buff = br.ReadBytes((int)numBytes);

            var path        = "container\\TestFolder\\test.jpeg";
            var file        = provider.CreateFile(path);
            var streamWrite = file.OpenWrite();
            var bw          = new BinaryWriter(streamWrite);

            bw.Write(buff);
            Assert.IsTrue(provider.ListFiles("container\\TestFolder\\").Any());
            provider.DeleteFile(path);
        }
예제 #16
0
        /// <summary>
        /// Creates an images thumbnail.
        /// </summary>
        /// <param name="image">The image full path on the media storage.</param>
        /// <param name="thumbnailFolderPath">The media path to thumbnails folder.</param>
        /// <param name="imageName">The image name.</param>
        /// <param name="thumbnailWidth">The thumbnail width in pixels.</param>
        /// <param name="thumbnailHeight">The thumbnail height in pixels.</param>
        /// <param name="keepAspectRatio">Indicates whether to keep the original image aspect ratio</param>
        /// <param name="expandToFill">Indicates whether to expand the thumbnail to fill the bounds specified by width and height</param>
        /// <returns>The thumbnail file media path.</returns>
        protected Thumbnail CreateThumbnail(string image, string thumbnailFolderPath, string imageName, int thumbnailWidth,
                                            int thumbnailHeight, bool keepAspectRatio, bool expandToFill)
        {
            if (thumbnailWidth <= 0)
            {
                throw new ArgumentException("Thumbnail width must be greater than zero", "thumbnailWidth");
            }

            if (thumbnailHeight <= 0)
            {
                throw new ArgumentException("Thumbnail height must be greater than zero", "thumbnailHeight");
            }

            string thumbnailFilePath = _storageProvider.Combine(thumbnailFolderPath, imageName);

            IStorageFile imageFile = _storageProvider.GetFile(image);

            using (Stream imageStream = imageFile.OpenRead()) {
                using (Image drawingImage = Image.FromStream(imageStream))
                {
                    bool shouldCreateImage = true;

                    // Verify if the image already has a Thumbnail
                    var thumbnailName = _mediaService.GetMediaFiles(thumbnailFolderPath)
                                        .Select(o => o.Name).SingleOrDefault(o => o == imageName);

                    if (thumbnailName != null)
                    {
                        // Verify if the existing thumbnail has the correct size (in case the thumbnail settings have been changed)
                        IStorageFile thumbnailFile = _storageProvider.GetFile(thumbnailFilePath);
                        using (Stream thumnailFileStream = thumbnailFile.OpenRead()) {
                            using (Image thumbnailImage = Image.FromStream(thumnailFileStream)) {
                                if (ImageHasCorrectThumbnail(drawingImage, thumbnailImage, thumbnailWidth, thumbnailHeight, keepAspectRatio, expandToFill))
                                {
                                    shouldCreateImage = false;
                                    thumbnailWidth    = thumbnailImage.Width;
                                    thumbnailHeight   = thumbnailImage.Height;
                                }
                            }
                        }
                    }

                    if (shouldCreateImage)
                    {
                        using (Image thumbDrawing = CreateThumbnail(drawingImage, thumbnailWidth, thumbnailHeight, keepAspectRatio, expandToFill)) {
                            if (_storageProvider.ListFiles(thumbnailFolderPath).Select(o => o.GetName()).Contains(imageName))
                            {
                                _storageProvider.DeleteFile(thumbnailFilePath);
                            }

                            IStorageFile thumbFile = _storageProvider.CreateFile(thumbnailFilePath);
                            using (Stream thumbStream = thumbFile.OpenWrite())
                            {
                                thumbDrawing.Save(thumbStream, _thumbnailImageFormat);
                                thumbnailWidth  = thumbDrawing.Width;
                                thumbnailHeight = thumbDrawing.Height;
                            }
                        }
                    }
                }
            }

            string thumbnailPublicUrl = _mediaService.GetMediaPublicUrl(Path.GetDirectoryName(thumbnailFilePath), Path.GetFileName(thumbnailFilePath));

            return(new Thumbnail {
                PublicUrl = thumbnailPublicUrl, Width = thumbnailWidth, Height = thumbnailHeight
            });
        }
예제 #17
0
 public static FileInfo GetOrCreateFile(this IStorageProvider storageProvider, string path)
 {
     return(!storageProvider.FileExists(path) ? storageProvider.CreateFile(path) : storageProvider.GetFile(path));
 }
        public void create_write_read_file_should_equal()
        {
            using (var stream = SUT.CreateFile(SUT.Combine(TEST_FOLDER, "test.txt")).OpenWrite())
            {
                stream.Write(new byte[] { 1 }, 0, 1);
            }

            using (var stream = SUT.GetFile(SUT.Combine(TEST_FOLDER, "test.txt")).OpenRead())
            {
                var buffer = new byte[1];
                stream.Read(buffer, 0, 1);

                Assert.AreEqual(1, buffer[0]);
            }
        }
예제 #19
0
        protected override DriverResult Editor(ContentPart part, Fields.FileField field, IUpdateModel updater, dynamic shapeHelper)
        {
            var settings  = field.PartFieldDefinition.Settings.GetModel <FileFieldSettings>();
            var viewModel = new FileFieldViewModel
            {
                Settings = settings,
                Field    = field
            };

            if (updater.TryUpdateModel(viewModel, GetPrefix(field, part), null, null))
            {
                var postedFile = ((Controller)updater).Request.Files["FileField-" + field.Name];

                AssignDefaultMediaFolder(settings);

                var mediaFolder = FormatWithTokens(settings.MediaFolder, part.ContentItem.ContentType, field.Name, part.ContentItem.Id);

                if (postedFile != null && postedFile.ContentLength != 0)
                {
                    var extension         = ParseFileExtenstion(postedFile.FileName);
                    var allowedExtensions = ParseAllowedExtention(settings.ExtenstionsAllowed);
                    var fileName          = Path.GetFileNameWithoutExtension(postedFile.FileName);

                    if (allowedExtensions.Contains(extension))
                    {
                        if (postedFile.ContentLength <= (settings.MaxFileSize * 1024))
                        {
                            var postedFileLength = postedFile.ContentLength;
                            var postedFileData   = new byte[postedFileLength];
                            var postedFileStream = postedFile.InputStream;
                            postedFileStream.Read(postedFileData, 0, postedFileLength);


                            try
                            {
                                // try to create the folder before uploading a file into it
                                _storageProvider.CreateFolder(mediaFolder);
                            }
                            catch
                            {
                                // the folder can't be created because it already exists, continue
                            }

                            if (settings.NameTag == NameTags.Index)
                            {
                                var lastFileIndex =
                                    _storageProvider.ListFiles(mediaFolder)
                                    .Count(f => Path.GetFileNameWithoutExtension(f.GetName()).Contains(fileName));

                                fileName = String.Format("{0} ({1}).{2}", fileName, lastFileIndex + 1, extension);
                            }
                            else if (settings.NameTag == NameTags.TimeStamp)
                            {
                                fileName = String.Format("{0}-{1}.{2}", fileName,
                                                         DateTime.Now.ToString("yyyyMMddhhmmss"), extension);
                            }

                            //
                            var filePath = _storageProvider.Combine(mediaFolder, fileName);
                            var file     = _storageProvider.CreateFile(filePath);
                            using (var fileStream = file.OpenWrite())
                            {
                                fileStream.Write(postedFileData, 0, postedFileLength);
                            }

                            field.Path = _storageProvider.GetPublicUrl(file.GetPath());
                        }
                        else
                        {
                            updater.AddModelError("File", T("The file size is bigger than the maximum file size, maximum size is {0}KB.", settings.MaxFileSize));
                        }
                    }
                    else
                    {
                        updater.AddModelError("File", T("The file type is not allowed for {0}.", postedFile.FileName));
                    }
                }
                else
                {
                    if (settings.Required && string.IsNullOrWhiteSpace(field.Path))
                    {
                        updater.AddModelError("File", T("You must provide a file for {0}.", field.Name.CamelFriendly()));
                    }
                }

                if (string.IsNullOrWhiteSpace(field.Text))
                {
                    field.Text = Path.GetFileName(field.Path);
                }
            }

            return(Editor(part, field, shapeHelper));
        }
        // Creating/writing some files. Don't forget to check them out after running this action in the Media folder!
        // You can access this action under ~/OrchardHUN.TrainingDemo/FileManagement/Create
        public string Create()
        {
            // Brace yourself, simple examples are coming!

            try
            {
                // The paths used as arguments here are relative to the tenant's media folder: this translates to
                // ~/Media/TenantName/DemoFolder/MyFile.txt where TenantName is the tenant's technical name ("Default" if for the first tenant).
                IStorageFile file;
                if (!_storageProvider.FileExists(DemoFile1Path))
                {
                    file = _storageProvider.CreateFile(DemoFile1Path);
                }
                else
                {
                    file = _storageProvider.GetFile(DemoFile1Path);
                }
                // Notice that the DemoFolder folder is implicitly created if it doesn't exist but we could explicitly create folder with
                // _storageProvider.CreateFolder("FolderPath");

                // Simple interface for writing...
                using (var stream = file.OpenWrite())
                    using (var streamWriter = new StreamWriter(stream))
                    {
                        streamWriter.Write("Hello there!");
                    }

                // Equivalent shorthand for creating a file. SaveStream() will throw an exception if the file exists.
                using (var stream = new MemoryStream())
                    using (var streamWriter = new StreamWriter(stream))
                    {
                        streamWriter.Write("Hello there!");
                        _storageProvider.SaveStream(DemoFile2Path, stream);
                        // SaveStream has a counterpart, TrySaveStream that returns a bool indicating whether the operation was successful or not, it
                        // doesn't throw an exception if the file exists. However internally it also catches exceptions...
                    }

                // ...and equally for reading.
                // OpenRead() throws an exception if the file doesn't exist.
                using (var stream = file.OpenRead())
                    using (var streamReader = new StreamReader(stream))
                    {
                        var content = streamReader.ReadToEnd();
                        // If you don't have to choose a specific exception class for throwing and exception, you should use
                        // OrchardException, for its message is localizable.
                        if (!content.Equals("Hello there!"))
                        {
                            throw new OrchardException(T("Well, this is awkward."));
                        }
                    }

                // Renaming is nothing special.
                _storageProvider.RenameFile(DemoFile2Path, DemoFolderPath + "HiddenSecretDontOpen.txt");

                // Fetching the public URL of the file. We can use this to access the file from the outside world, e.g. from a link.
                return(_storageProvider.GetPublicUrl(DemoFile1Path));
            }
            catch (Exception ex)
            {
                // Sometimes we can't know what type of exception a service can throw so the best we can do is catch
                // Exception and then check whether it's fatal.
                // For clarification see: http://english.orchardproject.hu/blog/orchard-gems-exception-fatality-check
                if (ex.IsFatal())
                {
                    throw;
                }

                return("Something went terribly wrong: " + ex.Message);
            }
        }
예제 #21
0
        public void Save(string fingerprint, CombinatorResource resource, ICombinatorSettings settings)
        {
            if (settings.EnableResourceSharing && CallOnDefaultShell(cacheFileService => cacheFileService.Save(fingerprint, resource, new CombinatorSettings(settings)
            {
                EnableResourceSharing = false
            })))
            {
                return;
            }

            var sliceCount = _fileRepository.Count(file => file.Fingerprint == ConvertFingerprintToStorageFormat(fingerprint));

            if (resource.LastUpdatedUtc == DateTime.MinValue)
            {
                resource.LastUpdatedUtc = _clock.UtcNow;
            }

            // Ceil-ing timestamp to the second, because sub-second precision is not stored in the DB. This would cause a discrepancy between saved
            // and fetched vs freshly created date times, causing unwanted cache busting for the same resource.
            resource.LastUpdatedUtc = new DateTime(resource.LastUpdatedUtc.Year, resource.LastUpdatedUtc.Month, resource.LastUpdatedUtc.Day, resource.LastUpdatedUtc.Hour, resource.LastUpdatedUtc.Minute, resource.LastUpdatedUtc.Second);

            var fileRecord = new CombinedFileRecord()
            {
                Fingerprint    = ConvertFingerprintToStorageFormat(fingerprint),
                Slice          = ++sliceCount,
                Type           = resource.Type,
                LastUpdatedUtc = resource.LastUpdatedUtc,
                Settings       = _combinatorResourceManager.SerializeResourceSettings(resource)
            };

            _fileRepository.Create(fileRecord);

            if (!string.IsNullOrEmpty(resource.Content))
            {
                var path = MakePath(fileRecord);

                if (_storageProvider.FileExists(path))
                {
                    _storageProvider.DeleteFile(path);
                }

                using (var stream = _storageProvider.CreateFile(path).OpenWrite())
                {
                    var bytes = Encoding.UTF8.GetBytes(resource.Content);
                    stream.Write(bytes, 0, bytes.Length);
                }

                if (!resource.IsRemoteStorageResource)
                {
                    // This is needed to adjust relative paths if the resource is stored in a remote storage provider.
                    // Why the double-saving? Before saving the file there is no reliable way to tell whether the storage public url will be a
                    // remote one or not...
                    var testResource = _combinatorResourceManager.ResourceFactory(resource.Type);
                    testResource.FillRequiredContext("TestCombinedResource", _storageProvider.GetPublicUrl(path));
                    _combinatorResourceManager.DeserializeSettings(fileRecord.Settings, testResource);
                    testResource.IsRemoteStorageResource = settings.RemoteStorageUrlPattern != null && settings.RemoteStorageUrlPattern.IsMatch(testResource.AbsoluteUrl.ToString());
                    if (testResource.IsRemoteStorageResource)
                    {
                        _storageProvider.DeleteFile(path);

                        testResource.Content = resource.Content;
                        var relativeUrlsBaseUri = settings.ResourceBaseUri != null ? settings.ResourceBaseUri : new Uri(_urlHelper.RequestContext.HttpContext.Request.Url, _urlHelper.Content("~/"));
                        ResourceProcessingService.RegexConvertRelativeUrlsToAbsolute(testResource, relativeUrlsBaseUri);

                        using (var stream = _storageProvider.CreateFile(path).OpenWrite())
                        {
                            var bytes = Encoding.UTF8.GetBytes(testResource.Content);
                            stream.Write(bytes, 0, bytes.Length);
                        }

                        resource.IsRemoteStorageResource = true;
                        fileRecord.Settings = _combinatorResourceManager.SerializeResourceSettings(resource);
                    }
                }
            }

            _combinatorEventHandler.BundleChanged(fingerprint);
        }
예제 #22
0
 public Task CreateFile(IStorageDirectory directory, string name, Stream file)
 {
     return(_provider.CreateFile(directory, name, file));
 }