public static void Move(this IFileSystem sourceFileSystem, FileSystemPath sourcePath, IFileSystem destinationFileSystem, FileSystemPath destinationPath)
 {
     IEntityMover mover;
     if (!EntityMovers.Registration.TryGetSupported(sourceFileSystem.GetType(), destinationFileSystem.GetType(), out mover))
         throw new ArgumentException("The specified combination of file-systems is not supported.");
     mover.Move(sourceFileSystem, sourcePath, destinationFileSystem, destinationPath);
 }
 /// <summary>
 /// Copies an entity from this file system to a destination file system (async with cancellation token).
 /// </summary>
 public static Task CopyAsync(this IFileSystem sourceFileSystem, FileSystemPath sourcePath, IFileSystem destinationFileSystem, FileSystemPath destinationPath, CancellationToken cancellationToken)
 {
     if (!EntityCopiers.Registration.TryGetSupported(sourceFileSystem.GetType(), destinationFileSystem.GetType(), out var copier))
     {
         throw new ArgumentException("The specified combination of file-systems is not supported.");
     }
     return(copier.CopyAsync(sourceFileSystem, sourcePath, destinationFileSystem, destinationPath, cancellationToken));
 }
Example #3
0
 // ReSharper disable once MemberCanBePrivate.Global
 public static void Move(this IFileSystem sourceFileSystem, FileSystemPath sourcePath, IFileSystem destinationFileSystem, FileSystemPath destinationPath)
 {
     if (!EntityMovers.Registration.TryGetSupported(sourceFileSystem.GetType(), destinationFileSystem.GetType(), out var mover))
     {
         throw new ArgumentException("The specified combination of file-systems is not supported.");
     }
     mover.Move(sourceFileSystem, sourcePath, destinationFileSystem, destinationPath);
 }
        public static void Copy(this IFileSystem sourceFileSystem, FileSystemPath sourcePath, IFileSystem destinationFileSystem, FileSystemPath destinationPath)
        {
            IEntityCopier copier;

            if (!EntityCopiers.Registration.TryGetSupported(sourceFileSystem.GetType(), destinationFileSystem.GetType(), out copier))
            {
                throw new ArgumentException("The specified combination of file-systems is not supported.");
            }
            copier.Copy(sourceFileSystem, sourcePath, destinationFileSystem, destinationPath);
        }
Example #5
0
        public static UPath GetTargetPath(this IFileSystem fileSystem,
                                          UPath virtualPath)
        {
            if (fileSystem is IJunctionPointFeature junctionPointFeature)
            {
                return(junctionPointFeature.GetJunctionTargetPath(virtualPath));
            }

            throw new NotSupportedException(
                      $"Junction point is not supported in file system {fileSystem.GetType().Name}");
        }
Example #6
0
        public static void DeleteJunctionPoint(this IFileSystem fileSystem,
                                               UPath virtualPath)
        {
            if (fileSystem is IJunctionPointFeature junctionPointFeature)
            {
                junctionPointFeature.DeleteJunctionPoint(virtualPath);
                return;
            }

            throw new NotSupportedException(
                      $"Junction point is not supported in file system {fileSystem.GetType().Name}");
        }
Example #7
0
        public static void CreateJunctionPoint(this IFileSystem fileSystem,
                                               JunctionPoint junctionPoint,
                                               bool overwrite)
        {
            if (fileSystem is IJunctionPointFeature junctionPointFeature)
            {
                junctionPointFeature.CreateJunctionPoint(junctionPoint, overwrite);
                return;
            }

            throw new NotSupportedException(
                      $"Junction point is not supported in file system {fileSystem.GetType().Name}");
        }
Example #8
0
        private IFileSystem getFileSystem(IConfigSectionNode mNode,
                                          out FileSystemSessionConnectParams cParams)
        {
            IFileSystem result = null;

            writeLog(MessageType.Info, "Making metabase FS instance...");

            var fsNode = mNode[CONFIG_FS_SECTION];

            var fsFallbackTypeName = Environment.GetEnvironmentVariable(ENV_VAR_METABASE_FS_TYPE);
            var fsFallbackType     = typeof(IO.FileSystem.Local.LocalFileSystem);

            if (fsFallbackTypeName.IsNotNullOrWhiteSpace())
            {
                fsFallbackType = Type.GetType(fsFallbackTypeName, true);
            }

            result = FactoryUtils.MakeAndConfigure <FileSystem>(fsNode,
                                                                fsFallbackType,
                                                                args: new object[] { CONFIG_METABASE_SECTION, fsNode });

            var paramsNode = fsNode[CONFIG_SESSION_CONNECT_PARAMS_SECTION];

            if (paramsNode.Exists)
            {
                cParams = FileSystemSessionConnectParams.Make <FileSystemSessionConnectParams>(paramsNode);
            }
            else
            {
                var fsFallbackCString = Environment.GetEnvironmentVariable(ENV_VAR_METABASE_FS_CSTRING);
                if (fsFallbackCString.IsNotNullOrWhiteSpace())
                {
                    cParams = FileSystemSessionConnectParams.Make <FileSystemSessionConnectParams>(fsFallbackCString);
                }
                else
                {
                    cParams = new FileSystemSessionConnectParams()
                    {
                        User = User.Fake
                    }
                };
            }

            writeLog(MessageType.Info, "...Metabase FS FileSystemSessionConnectParams instance of '{0}' made".Args(cParams.GetType().FullName));
            writeLog(MessageType.Info, "...Metabase FS instance of '{0}' made".Args(result.GetType().FullName));

            return(result);
        }
Example #9
0
 public bool NeedToCopy(FolderMap baseMap, string aSource, string aTarget)
 {
     Logger.Debug($"aSource={aSource}, aTarget={aTarget}");
     Logger.Debug($"TypeOf(_fileSystem)={_fileSystem.GetType()} ");
     if (!_fileSystem.File.Exists(aTarget))
     {
         Logger.Debug($"File {aTarget} not found! Need to copy.");
         return true;
     }
     else if (_fileComparer.IsSameFile(new FileInfo(aSource), new FileInfo(aTarget)))
     {
         Logger.Debug($"File {aTarget} equal to {aSource}! Skip file!");
         return false;
     }
     return _confirmationChecker.GetConfirmation(aTarget);
 }
Example #10
0
        /// <summary>
        /// Overridable method to execute when All resolvers have been initialized but resolution is not
        /// frozen so they can be modified in this method
        /// </summary>
        /// <param name="umbracoApplication">The current <see cref="UmbracoApplicationBase"/></param>
        /// <param name="applicationContext">The Umbraco <see cref="ApplicationContext"/> for the current application.</param>
        protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            bool disable = ConfigurationManager.AppSettings[DisableVirtualPathProviderKey] != null &&
                           ConfigurationManager.AppSettings[DisableVirtualPathProviderKey]
                           .Equals("true", StringComparison.InvariantCultureIgnoreCase);

            IFileSystem fileSystem            = FileSystemProviderManager.Current.GetUnderlyingFileSystemProvider("media");
            bool        isAzureBlobFileSystem = fileSystem.GetType() == typeof(AzureBlobFileSystem);

            if (!disable && isAzureBlobFileSystem)
            {
                FileSystemVirtualPathProvider.ConfigureMedia();
            }

            base.ApplicationStarting(umbracoApplication, applicationContext);
        }
        public string CopyToDb()
        {
            if (fs.GetType() != typeof(DatabaseFileSystem))
            {
                throw new Exception("Database filesystem not configured");
            }

            var uploadFolders = folderSource.GetUploadFoldersForAllSites();

            foreach (var uploadFolder in uploadFolders)
            {
                CopyFilesInDirectoryRecursively(webContext.MapPath(uploadFolder));
            }

            return(returnValue);
        }
Example #12
0
        protected override BatchJobExecutionResult OnExecute(MigrateFilesBatchJob batchJob)
        {
            List <Guid> guids = JsonConvert.DeserializeObject <HashSet <Guid> >(batchJob.Data).ToList();

            IList <MediaFile> mediaFiles = _session.QueryOver <MediaFile>().Where(x => x.Guid.IsIn(guids)).List();


            foreach (MediaFile mediaFile in mediaFiles)
            {
                IFileSystem from = MediaFileExtensions.GetFileSystem(mediaFile.FileUrl, _fileSystems);
                IFileSystem to   = CurrentFileSystem;
                if (from.GetType() == to.GetType())
                {
                    continue;
                }

                _session.Transact(session =>
                {
                    // remove resized images (they will be regenerated on the to system)
                    foreach (ResizedImage resizedImage in mediaFile.ResizedImages.ToList())
                    {
                        // check for resized file having same url as the original -
                        // do not delete from disc yet in that case, or else it will cause an error when copying
                        if (resizedImage.Url != mediaFile.FileUrl)
                        {
                            from.Delete(resizedImage.Url);
                        }
                        mediaFile.ResizedImages.Remove(resizedImage);
                        session.Delete(resizedImage);
                    }

                    string existingUrl = mediaFile.FileUrl;
                    using (System.IO.Stream readStream = @from.GetReadStream(existingUrl))
                    {
                        mediaFile.FileUrl = to.SaveFile(readStream, GetNewFilePath(mediaFile),
                                                        mediaFile.ContentType);
                    }
                    from.Delete(existingUrl);

                    session.Update(mediaFile);
                });
            }


            return(BatchJobExecutionResult.Success());
        }
        public ReplicationStorageFileSystemN2(ContentActivator activator, IFileSystemFactory fsfactory, IDefinitionManager definitions, IPersister persister)
        {
            _activator = activator;
            _definitions = definitions;
            _persister = persister;

            string value = (ConfigurationManager.AppSettings["XmlReplication"] ?? "false").ToLowerInvariant();
            if (value.Equals("slave") || value.Equals("master"))
            {
                // only initialize if replication is active
                var storageConfig = (FileSystemNamespace) Enum.Parse(typeof (FileSystemNamespace),
                               ConfigurationManager.AppSettings["AzureReplicationStorageContainerName"] ?? "ReplicationStorageDebug");

                _fs = fsfactory.Create(storageConfig);

                if (_fs.GetType().Name.Contains("Azure"))
                    _path = "/_Xml_Sync_"; // TODO maybe should add TablePrefix?
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SubdirectoryFileSystem"/> class
        /// </summary>
        /// <param name="parentFileSystem">The file system to represent a subdirectory of.</param>
        /// <param name="dataStorePath">The (data store) path of the directory to represent.</param>
        public SubdirectoryFileSystem( IFileSystem parentFileSystem, string dataStorePath )
        {
            try
            {
                if( parentFileSystem.NullReference() )
                    throw new ArgumentNullException().StoreFileLine();

                if( !DataStore.IsValidPath(dataStorePath) ) // empty string is acceptable!
                    throw new ArgumentException().StoreFileLine();

                this.parentFileSystem = parentFileSystem;
                this.subDirPath = dataStorePath;
            }
            catch( Exception ex )
            {
                ex.StoreFileLine();
                ex.Store("parentFileSystemType", parentFileSystem.NullReference() ? null : parentFileSystem.GetType());
                ex.Store("dataStorePath", dataStorePath);
                throw;
            }
        }
        /// <summary>
        /// Attaches the given <paramref name="source"/> entry to <paramref name="fs"/> by checking
        /// whether source's origin file system root is underneath <paramref name="fs"/> and prepending
        /// the path difference to source's subpath.
        /// <para>
        /// Use this method if you - for example - want to copy directories across file system boundaries:
        /// </para>
        /// <para>
        /// <code>
        /// var sourceDir = _appContext.TenantRoot.GetDirectory("SourceDir");
        /// var targetDir = _appContext.WebRoot.GetDirectory("exchange");
        ///
        /// var attachedSourceDir = _appContext.ContentRoot.AttachEntry(sourceDir);
        /// var attachedTargetDir = _appContext.ContentRoot.AttachEntry(targetDir);
        ///
        /// _appContext.ContentRoot.CopyDirectory(attachedSourceDir.SubPath, attachedTargetDir.SubPath);
        /// </code>
        /// This method will throw if the involved file systems are of different type or if source file system is not underneath the target file system.
        /// </para>
        /// </summary>
        /// <typeparam name="TEntry">Entry type, either <see cref="IFile"/> or <see cref="IDirectory"/>.</typeparam>
        /// <param name="fs">The file system to attach the entry to.</param>
        /// <param name="source">The source entry to attach.</param>
        public static TEntry AttachEntry <TEntry>(this IFileSystem fs, TEntry source)
            where TEntry : IFileEntry
        {
            Guard.NotNull(fs, nameof(fs));
            Guard.NotNull(source, nameof(source));

            if (source.FileSystem == fs || source.FileSystem.Root.EqualsNoCase(fs.Root))
            {
                return(source);
            }

            if (source.FileSystem.GetType() != fs.GetType())
            {
                throw new FileSystemException("While attaching entries, both file system implementations must be of same type.");
            }

            if (!source.FileSystem.Root.StartsWith(fs.Root))
            {
                throw new FileSystemException($"The root of the source entry must be underneath the target file system root. Source: {source.FileSystem.Root}, Target: {fs.Root}");
            }

            var subRoot      = FileSystemBase.NormalizePath(source.FileSystem.Root[fs.Root.Length..]);
        public ReplicationStorageFileSystemN2(ContentActivator activator, IFileSystemFactory fsfactory, IDefinitionManager definitions, IPersister persister)
        {
            _activator   = activator;
            _definitions = definitions;
            _persister   = persister;

            string value = (ConfigurationManager.AppSettings["XmlReplication"] ?? "false").ToLowerInvariant();

            if (value.Equals("slave") || value.Equals("master"))
            {
                // only initialize if replication is active
                var storageConfig = (FileSystemNamespace)Enum.Parse(typeof(FileSystemNamespace),
                                                                    ConfigurationManager.AppSettings["AzureReplicationStorageContainerName"] ?? "ReplicationStorageDebug");

                _fs = fsfactory.Create(storageConfig);

                if (_fs.GetType().Name.Contains("Azure"))
                {
                    _path = "/_Xml_Sync_"; // TODO maybe should add TablePrefix?
                }
            }
        }
Example #17
0
 public override string GetItemImage(object item)
 {
     return(fileSystem.GetType().Name);
 }
 private static string CreateErrorMessage(IFileSystem fileSystem)
 {
     return(string.Format("The IFileSystem implementation is a {0} which is not supposed to be wrapped by TxFileSystem.",
                          fileSystem.GetType().Name));
 }
Example #19
0
        //tests and sets FS connection params
        private FileSystemSession ctorFS(IFileSystem fileSystem, FileSystemSessionConnectParams fsSessionParams, string rootPath)
        {
            FileSystemSession session = null;

            //Test FS connection
            try
            {
                session = fileSystem.StartSession(fsSessionParams);
                if (fsSessionParams.Version == null)
                {
                    fsSessionParams.Version = session.LatestVersion;
                }
            }
            catch (Exception error)
            {
                throw new MetabaseException(StringConsts.METABASE_FS_CONNECTION_ERROR.Args(fileSystem.GetType().FullName,
                                                                                           fileSystem.Name,
                                                                                           fsSessionParams.ToString(),
                                                                                           error.ToMessageWithType()
                                                                                           ), error);
            }

            m_FS = fileSystem;
            m_FSSessionConnectParams = fsSessionParams;
            m_FSRootPath             = rootPath ?? string.Empty;

            return(session);
        }