From 7b19ab005bff9a80f40638fe1e39ecc9481648ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B8ren=20Gregersen?= Date: Wed, 13 Nov 2019 21:00:54 +0100 Subject: [PATCH] first round of refactoring --- .../Compose/ManifestWatcherComponent.cs | 6 +- .../CompositionExtensions/FileSystems.cs | 2 +- .../CompositionExtensions/Services.cs | 12 +- src/Umbraco.Core/Composing/Current.cs | 1 + src/Umbraco.Core/ConfigsExtensions.cs | 6 +- .../Configuration/GlobalSettings.cs | 18 +- src/Umbraco.Core/ContentExtensions.cs | 4 +- src/Umbraco.Core/Diagnostics/MiniDump.cs | 9 +- src/Umbraco.Core/IO/FileSystems.cs | 26 +-- src/Umbraco.Core/IO/MediaFileSystem.cs | 8 +- src/Umbraco.Core/IO/PhysicalFileSystem.cs | 24 ++- src/Umbraco.Core/IO/ShadowWrapper.cs | 14 +- src/Umbraco.Core/IO/SystemDirectories.cs | 10 +- .../Logging/Viewer/JsonLogViewer.cs | 3 +- .../Logging/Viewer/LogViewerComposer.cs | 3 +- .../Logging/Viewer/LogViewerSourceBase.cs | 18 +- src/Umbraco.Core/Manifest/ManifestParser.cs | 14 +- .../Migrations/Install/DatabaseBuilder.cs | 24 +-- .../Packaging/PackageFileInstallation.cs | 10 +- .../Packaging/PackagesRepository.cs | 26 +-- .../Implement/PartialViewMacroRepository.cs | 4 +- .../Implement/PartialViewRepository.cs | 20 +- .../Implement/TemplateRepository.cs | 8 +- .../PropertyEditors/ConfigurationField.cs | 2 +- .../PropertyEditors/GridEditor.cs | 8 +- .../Runtime/CoreInitialComponent.cs | 17 +- src/Umbraco.Core/Runtime/CoreRuntime.cs | 2 +- .../Services/Implement/FileService.cs | 8 +- .../Services/Implement/NotificationService.cs | 8 +- .../Services/Implement/PackagingService.cs | 7 +- src/Umbraco.Core/StringExtensions.cs | 4 +- src/Umbraco.Core/UriExtensions.cs | 4 +- .../Components/ComponentTests.cs | 3 +- .../IO/PhysicalFileSystemTests.cs | 2 +- src/Umbraco.Tests/IO/ShadowFileSystemTests.cs | 177 +++++++++++------- src/Umbraco.Tests/Logging/LogviewerTests.cs | 7 +- .../Manifest/ManifestParserTests.cs | 3 +- src/Umbraco.Tests/Models/MediaXmlTest.cs | 3 +- .../Packaging/PackageInstallationTest.cs | 20 +- .../PartialViewRepositoryTests.cs | 4 +- .../Repositories/ScriptRepositoryTest.cs | 2 +- .../Repositories/StylesheetRepositoryTest.cs | 2 +- .../Repositories/TemplateRepositoryTest.cs | 6 +- .../PropertyEditors/ImageCropperTest.cs | 3 +- .../Scoping/ScopeEventDispatcherTests.cs | 2 +- .../Scoping/ScopeFileSystemsTests.cs | 16 +- src/Umbraco.Tests/TestHelpers/TestObjects.cs | 23 +-- src/Umbraco.Tests/Testing/UmbracoTestBase.cs | 3 +- .../Editors/BackOfficeAssetsController.cs | 9 +- src/Umbraco.Web/Trees/FilesTreeController.cs | 11 +- .../WebApi/HttpActionContextExtensions.cs | 4 +- 51 files changed, 388 insertions(+), 242 deletions(-) diff --git a/src/Umbraco.Core/Compose/ManifestWatcherComponent.cs b/src/Umbraco.Core/Compose/ManifestWatcherComponent.cs index 97e27e9e23..bb6df42c13 100644 --- a/src/Umbraco.Core/Compose/ManifestWatcherComponent.cs +++ b/src/Umbraco.Core/Compose/ManifestWatcherComponent.cs @@ -10,15 +10,17 @@ namespace Umbraco.Core.Compose { private readonly IRuntimeState _runtimeState; private readonly ILogger _logger; + private readonly IIOHelper _ioHelper; // if configured and in debug mode, a ManifestWatcher watches App_Plugins folders for // package.manifest chances and restarts the application on any change private ManifestWatcher _mw; - public ManifestWatcherComponent(IRuntimeState runtimeState, ILogger logger) + public ManifestWatcherComponent(IRuntimeState runtimeState, ILogger logger, IIOHelper ioHelper) { _runtimeState = runtimeState; _logger = logger; + _ioHelper = ioHelper; } public void Initialize() @@ -28,7 +30,7 @@ namespace Umbraco.Core.Compose //if (ApplicationContext.Current.IsConfigured == false || GlobalSettings.DebugMode == false) // return; - var appPlugins = Current.IOHelper.MapPath("~/App_Plugins/"); + var appPlugins = _ioHelper.MapPath("~/App_Plugins/"); if (Directory.Exists(appPlugins) == false) return; _mw = new ManifestWatcher(_logger); diff --git a/src/Umbraco.Core/Composing/CompositionExtensions/FileSystems.cs b/src/Umbraco.Core/Composing/CompositionExtensions/FileSystems.cs index 8518d907b5..cb83db5db0 100644 --- a/src/Umbraco.Core/Composing/CompositionExtensions/FileSystems.cs +++ b/src/Umbraco.Core/Composing/CompositionExtensions/FileSystems.cs @@ -90,7 +90,7 @@ namespace Umbraco.Core.Composing.CompositionExtensions // register the IFileSystem supporting the IMediaFileSystem // THIS IS THE ONLY THING THAT NEEDS TO CHANGE, IN ORDER TO REPLACE THE UNDERLYING FILESYSTEM // and, SupportingFileSystem.For() returns the underlying filesystem - composition.SetMediaFileSystem(() => new PhysicalFileSystem(SystemDirectories.Media)); + composition.SetMediaFileSystem(factory => new PhysicalFileSystem(SystemDirectories.Media, factory.GetInstance())); return composition; } diff --git a/src/Umbraco.Core/Composing/CompositionExtensions/Services.cs b/src/Umbraco.Core/Composing/CompositionExtensions/Services.cs index 9d7d0a191d..04028e4f31 100644 --- a/src/Umbraco.Core/Composing/CompositionExtensions/Services.cs +++ b/src/Umbraco.Core/Composing/CompositionExtensions/Services.cs @@ -71,7 +71,7 @@ namespace Umbraco.Core.Composing.CompositionExtensions new PackageInstallation( factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), - new DirectoryInfo(Current.IOHelper.GetRootDirectorySafe()))); + new DirectoryInfo( factory.GetInstance().GetRootDirectorySafe()))); return composition; } @@ -84,14 +84,16 @@ namespace Umbraco.Core.Composing.CompositionExtensions /// private static PackagesRepository CreatePackageRepository(IFactory factory, string packageRepoFileName) => new PackagesRepository( - factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), + factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), packageRepoFileName); private static LocalizedTextServiceFileSources SourcesFactory(IFactory container) { - var mainLangFolder = new DirectoryInfo(Current.IOHelper.MapPath(SystemDirectories.Umbraco + "/config/lang/")); - var appPlugins = new DirectoryInfo(Current.IOHelper.MapPath(SystemDirectories.AppPlugins)); - var configLangFolder = new DirectoryInfo(Current.IOHelper.MapPath(SystemDirectories.Config + "/lang/")); + var ioHelper = container.GetInstance(); + + var mainLangFolder = new DirectoryInfo(ioHelper.MapPath(SystemDirectories.Umbraco + "/config/lang/")); + var appPlugins = new DirectoryInfo(ioHelper.MapPath(SystemDirectories.AppPlugins)); + var configLangFolder = new DirectoryInfo(ioHelper.MapPath(SystemDirectories.Config + "/lang/")); var pluginLangFolders = appPlugins.Exists == false ? Enumerable.Empty() diff --git a/src/Umbraco.Core/Composing/Current.cs b/src/Umbraco.Core/Composing/Current.cs index 3f9c4db288..2b3cf30301 100644 --- a/src/Umbraco.Core/Composing/Current.cs +++ b/src/Umbraco.Core/Composing/Current.cs @@ -205,6 +205,7 @@ namespace Umbraco.Core.Composing public static IVariationContextAccessor VariationContextAccessor => Factory.GetInstance(); + [Obsolete("being removed...", true)] public static readonly IIOHelper IOHelper = new IOHelper(); #endregion diff --git a/src/Umbraco.Core/ConfigsExtensions.cs b/src/Umbraco.Core/ConfigsExtensions.cs index 10293d1171..87f0216b51 100644 --- a/src/Umbraco.Core/ConfigsExtensions.cs +++ b/src/Umbraco.Core/ConfigsExtensions.cs @@ -33,9 +33,11 @@ namespace Umbraco.Core public static void AddCoreConfigs(this Configs configs) { - var configDir = new DirectoryInfo(Current.IOHelper.MapPath(SystemDirectories.Config)); + var ioHelper = Current.Factory.GetInstance(); - configs.Add(() => new GlobalSettings()); + var configDir = new DirectoryInfo(ioHelper.MapPath(SystemDirectories.Config)); + + configs.Add(() => new GlobalSettings(ioHelper)); configs.Add("umbracoConfiguration/settings"); configs.Add("umbracoConfiguration/HealthChecks"); diff --git a/src/Umbraco.Core/Configuration/GlobalSettings.cs b/src/Umbraco.Core/Configuration/GlobalSettings.cs index f2438065a4..a0cf20b2e1 100644 --- a/src/Umbraco.Core/Configuration/GlobalSettings.cs +++ b/src/Umbraco.Core/Configuration/GlobalSettings.cs @@ -19,6 +19,7 @@ namespace Umbraco.Core.Configuration /// public class GlobalSettings : IGlobalSettings { + private readonly IIOHelper _ioHelper; private string _localTempPath; // TODO these should not be static @@ -29,6 +30,11 @@ namespace Umbraco.Core.Configuration internal const string StaticReservedPaths = "~/app_plugins/,~/install/,~/mini-profiler-resources/,"; //must end with a comma! internal const string StaticReservedUrls = "~/config/splashes/noNodes.aspx,~/.well-known,"; //must end with a comma! + public GlobalSettings(IIOHelper ioHelper) + { + _ioHelper = ioHelper; + } + /// /// Used in unit testing to reset all config items that were set with property setters (i.e. did not come from config) /// @@ -141,7 +147,7 @@ namespace Umbraco.Core.Configuration get { return ConfigurationManager.AppSettings.ContainsKey(Constants.AppSettings.Path) - ? Current.IOHelper.ResolveUrl(ConfigurationManager.AppSettings[Constants.AppSettings.Path]) + ? _ioHelper.ResolveUrl(ConfigurationManager.AppSettings[Constants.AppSettings.Path]) : string.Empty; } } @@ -171,7 +177,9 @@ namespace Umbraco.Core.Configuration /// Value of the setting to be saved. internal static void SaveSetting(string key, string value) { - var fileName = Current.IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root)); + var ioHelper = Current.Factory.GetInstance(); + + var fileName = ioHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root)); var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); var appSettings = xml.Root.DescendantsAndSelf("appSettings").Single(); @@ -191,9 +199,9 @@ namespace Umbraco.Core.Configuration /// Removes a setting from the configuration file. /// /// Key of the setting to be removed. - internal static void RemoveSetting(string key) + internal static void RemoveSetting(string key, IIOHelper ioHelper) { - var fileName = Current.IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root)); + var fileName = ioHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root)); var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); var appSettings = xml.Root.DescendantsAndSelf("appSettings").Single(); @@ -320,7 +328,7 @@ namespace Umbraco.Core.Configuration //case LocalTempStorage.Default: //case LocalTempStorage.Unknown: default: - return _localTempPath = Current.IOHelper.MapPath("~/App_Data/TEMP"); + return _localTempPath = _ioHelper.MapPath("~/App_Data/TEMP"); } } } diff --git a/src/Umbraco.Core/ContentExtensions.cs b/src/Umbraco.Core/ContentExtensions.cs index 8e404402d0..6195d68a13 100644 --- a/src/Umbraco.Core/ContentExtensions.cs +++ b/src/Umbraco.Core/ContentExtensions.cs @@ -148,7 +148,9 @@ namespace Umbraco.Core if (filename == null || filestream == null) return; // get a safe & clean filename - filename = Current.IOHelper.SafeFileName(filename); + var ioHelper = Current.Factory.GetInstance(); + + filename = ioHelper.SafeFileName(filename); if (string.IsNullOrWhiteSpace(filename)) return; filename = filename.ToLower(); diff --git a/src/Umbraco.Core/Diagnostics/MiniDump.cs b/src/Umbraco.Core/Diagnostics/MiniDump.cs index 92b6e8cbda..6534ad705c 100644 --- a/src/Umbraco.Core/Diagnostics/MiniDump.cs +++ b/src/Umbraco.Core/Diagnostics/MiniDump.cs @@ -110,11 +110,13 @@ namespace Umbraco.Core.Diagnostics // filter everywhere in our code = not! var stacktrace = withException ? Environment.StackTrace : string.Empty; - var filepath = Current.IOHelper.MapPath("~/App_Data/MiniDump"); + var ioHelper = Current.Factory.GetInstance(); + + var filepath = ioHelper.MapPath("~/App_Data/MiniDump"); if (Directory.Exists(filepath) == false) Directory.CreateDirectory(filepath); - var filename = Path.Combine(filepath, string.Format("{0:yyyyMMddTHHmmss}.{1}.dmp", DateTime.UtcNow, Guid.NewGuid().ToString("N").Substring(0, 4))); + var filename = Path.Combine(filepath, $"{DateTime.UtcNow:yyyyMMddTHHmmss}.{Guid.NewGuid().ToString("N").Substring(0, 4)}.dmp"); using (var stream = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite, FileShare.Write)) { return Write(stream.SafeFileHandle, options, withException); @@ -126,7 +128,8 @@ namespace Umbraco.Core.Diagnostics { lock (LockO) { - var filepath = Current.IOHelper.MapPath("~/App_Data/MiniDump"); + var ioHelper = Current.Factory.GetInstance(); + var filepath = ioHelper.MapPath("~/App_Data/MiniDump"); if (Directory.Exists(filepath) == false) return true; var count = Directory.GetFiles(filepath, "*.dmp").Length; return count < 8; diff --git a/src/Umbraco.Core/IO/FileSystems.cs b/src/Umbraco.Core/IO/FileSystems.cs index 8906752dd1..0350c3a606 100644 --- a/src/Umbraco.Core/IO/FileSystems.cs +++ b/src/Umbraco.Core/IO/FileSystems.cs @@ -11,6 +11,7 @@ namespace Umbraco.Core.IO { private readonly IFactory _container; private readonly ILogger _logger; + private readonly IIOHelper _ioHelper; private readonly ConcurrentDictionary> _filesystems = new ConcurrentDictionary>(); @@ -33,10 +34,11 @@ namespace Umbraco.Core.IO #region Constructor // DI wants a public ctor - public FileSystems(IFactory container, ILogger logger) + public FileSystems(IFactory container, ILogger logger, IIOHelper ioHelper) { _container = container; _logger = logger; + _ioHelper = ioHelper; } // for tests only, totally unsafe @@ -120,17 +122,17 @@ namespace Umbraco.Core.IO // but it does not really matter what we return - here, null private object CreateWellKnownFileSystems() { - var macroPartialFileSystem = new PhysicalFileSystem(SystemDirectories.MacroPartials); - var partialViewsFileSystem = new PhysicalFileSystem(SystemDirectories.PartialViews); - var stylesheetsFileSystem = new PhysicalFileSystem(SystemDirectories.Css); - var scriptsFileSystem = new PhysicalFileSystem(SystemDirectories.Scripts); - var mvcViewsFileSystem = new PhysicalFileSystem(SystemDirectories.MvcViews); + var macroPartialFileSystem = new PhysicalFileSystem(SystemDirectories.MacroPartials, _ioHelper); + var partialViewsFileSystem = new PhysicalFileSystem(SystemDirectories.PartialViews, _ioHelper); + var stylesheetsFileSystem = new PhysicalFileSystem(SystemDirectories.Css, _ioHelper); + var scriptsFileSystem = new PhysicalFileSystem(SystemDirectories.Scripts, _ioHelper); + var mvcViewsFileSystem = new PhysicalFileSystem(SystemDirectories.MvcViews, _ioHelper); - _macroPartialFileSystem = new ShadowWrapper(macroPartialFileSystem, "macro-partials", IsScoped); - _partialViewsFileSystem = new ShadowWrapper(partialViewsFileSystem, "partials", IsScoped); - _stylesheetsFileSystem = new ShadowWrapper(stylesheetsFileSystem, "css", IsScoped); - _scriptsFileSystem = new ShadowWrapper(scriptsFileSystem, "scripts", IsScoped); - _mvcViewsFileSystem = new ShadowWrapper(mvcViewsFileSystem, "views", IsScoped); + _macroPartialFileSystem = new ShadowWrapper(macroPartialFileSystem, "macro-partials", _ioHelper, IsScoped); + _partialViewsFileSystem = new ShadowWrapper(partialViewsFileSystem, "partials", _ioHelper, IsScoped); + _stylesheetsFileSystem = new ShadowWrapper(stylesheetsFileSystem, "css", _ioHelper, IsScoped); + _scriptsFileSystem = new ShadowWrapper(scriptsFileSystem, "scripts", _ioHelper, IsScoped); + _mvcViewsFileSystem = new ShadowWrapper(mvcViewsFileSystem, "views", _ioHelper, IsScoped); // TODO: do we need a lock here? _shadowWrappers.Add(_macroPartialFileSystem); @@ -269,7 +271,7 @@ namespace Umbraco.Core.IO { lock (_shadowLocker) { - var wrapper = new ShadowWrapper(filesystem, shadowPath, IsScoped); + var wrapper = new ShadowWrapper(filesystem, shadowPath, _ioHelper, IsScoped); if (_shadowCurrentId != null) wrapper.Shadow(_shadowCurrentId); _shadowWrappers.Add(wrapper); diff --git a/src/Umbraco.Core/IO/MediaFileSystem.cs b/src/Umbraco.Core/IO/MediaFileSystem.cs index 2de7bc2f81..4ac9ca99b0 100644 --- a/src/Umbraco.Core/IO/MediaFileSystem.cs +++ b/src/Umbraco.Core/IO/MediaFileSystem.cs @@ -22,16 +22,18 @@ namespace Umbraco.Core.IO private readonly IMediaPathScheme _mediaPathScheme; private readonly IContentSection _contentConfig; private readonly ILogger _logger; + private readonly IIOHelper _ioHelper; /// /// Initializes a new instance of the class. /// - public MediaFileSystem(IFileSystem innerFileSystem, IContentSection contentConfig, IMediaPathScheme mediaPathScheme, ILogger logger) + public MediaFileSystem(IFileSystem innerFileSystem, IContentSection contentConfig, IMediaPathScheme mediaPathScheme, ILogger logger, IIOHelper ioHelper) : base(innerFileSystem) { _contentConfig = contentConfig; _mediaPathScheme = mediaPathScheme; _logger = logger; + _ioHelper = ioHelper; } /// @@ -68,7 +70,7 @@ namespace Umbraco.Core.IO { filename = Path.GetFileName(filename); if (filename == null) throw new ArgumentException("Cannot become a safe filename.", nameof(filename)); - filename = Current.IOHelper.SafeFileName(filename.ToLowerInvariant()); + filename = _ioHelper.SafeFileName(filename.ToLowerInvariant()); return _mediaPathScheme.GetFilePath(this, cuid, puid, filename); } @@ -78,7 +80,7 @@ namespace Umbraco.Core.IO { filename = Path.GetFileName(filename); if (filename == null) throw new ArgumentException("Cannot become a safe filename.", nameof(filename)); - filename = Current.IOHelper.SafeFileName(filename.ToLowerInvariant()); + filename = _ioHelper.SafeFileName(filename.ToLowerInvariant()); return _mediaPathScheme.GetFilePath(this, cuid, puid, filename, prevpath); } diff --git a/src/Umbraco.Core/IO/PhysicalFileSystem.cs b/src/Umbraco.Core/IO/PhysicalFileSystem.cs index 2e133a03c3..4fc502e63f 100644 --- a/src/Umbraco.Core/IO/PhysicalFileSystem.cs +++ b/src/Umbraco.Core/IO/PhysicalFileSystem.cs @@ -11,6 +11,8 @@ namespace Umbraco.Core.IO { public class PhysicalFileSystem : IFileSystem { + private readonly IIOHelper _ioHelper; + // the rooted, filesystem path, using directory separator chars, NOT ending with a separator // eg "c:" or "c:\path\to\site" or "\\server\path" private readonly string _rootPath; @@ -26,28 +28,32 @@ namespace Umbraco.Core.IO // virtualRoot should be "~/path/to/root" eg "~/Views" // the "~/" is mandatory. - public PhysicalFileSystem(string virtualRoot) + public PhysicalFileSystem(string virtualRoot, IIOHelper ioHelper) { if (virtualRoot == null) throw new ArgumentNullException("virtualRoot"); if (virtualRoot.StartsWith("~/") == false) throw new ArgumentException("The virtualRoot argument must be a virtual path and start with '~/'"); - _rootPath = EnsureDirectorySeparatorChar(Current.IOHelper.MapPath(virtualRoot)).TrimEnd(Path.DirectorySeparatorChar); + _ioHelper = ioHelper; + + _rootPath = EnsureDirectorySeparatorChar(ioHelper.MapPath(virtualRoot)).TrimEnd(Path.DirectorySeparatorChar); _rootPathFwd = EnsureUrlSeparatorChar(_rootPath); - _rootUrl = EnsureUrlSeparatorChar(Current.IOHelper.ResolveUrl(virtualRoot)).TrimEnd('/'); + _rootUrl = EnsureUrlSeparatorChar(ioHelper.ResolveUrl(virtualRoot)).TrimEnd('/'); } - public PhysicalFileSystem(string rootPath, string rootUrl) + public PhysicalFileSystem(string rootPath, string rootUrl, IIOHelper ioHelper) { if (string.IsNullOrEmpty(rootPath)) throw new ArgumentNullOrEmptyException(nameof(rootPath)); if (string.IsNullOrEmpty(rootUrl)) throw new ArgumentNullOrEmptyException(nameof(rootUrl)); if (rootPath.StartsWith("~/")) throw new ArgumentException("The rootPath argument cannot be a virtual path and cannot start with '~/'"); + _ioHelper = ioHelper; + // rootPath should be... rooted, as in, it's a root path! if (Path.IsPathRooted(rootPath) == false) { // but the test suite App.config cannot really "root" anything so we have to do it here - var localRoot = Current.IOHelper.GetRootDirectorySafe(); + var localRoot = _ioHelper.GetRootDirectorySafe(); rootPath = Path.Combine(localRoot, rootPath); } @@ -257,12 +263,12 @@ namespace Umbraco.Core.IO // if it starts with the root url, strip it and trim the starting slash to make it relative // eg "/Media/1234/img.jpg" => "1234/img.jpg" - if (Current.IOHelper.PathStartsWith(path, _rootUrl, '/')) + if (_ioHelper.PathStartsWith(path, _rootUrl, '/')) return path.Substring(_rootUrl.Length).TrimStart('/'); // if it starts with the root path, strip it and trim the starting slash to make it relative // eg "c:/websites/test/root/Media/1234/img.jpg" => "1234/img.jpg" - if (Current.IOHelper.PathStartsWith(path, _rootPathFwd, '/')) + if (_ioHelper.PathStartsWith(path, _rootPathFwd, '/')) return path.Substring(_rootPathFwd.Length).TrimStart('/'); // unchanged - what else? @@ -292,7 +298,7 @@ namespace Umbraco.Core.IO path = GetRelativePath(path); // if not already rooted, combine with the root path - if (Current.IOHelper.PathStartsWith(path, _rootPath, Path.DirectorySeparatorChar) == false) + if (_ioHelper.PathStartsWith(path, _rootPath, Path.DirectorySeparatorChar) == false) path = Path.Combine(_rootPath, path); // sanitize - GetFullPath will take care of any relative @@ -303,7 +309,7 @@ namespace Umbraco.Core.IO // at that point, path is within legal parts of the filesystem, ie we have // permissions to reach that path, but it may nevertheless be outside of // our root path, due to relative segments, so better check - if (Current.IOHelper.PathStartsWith(path, _rootPath, Path.DirectorySeparatorChar)) + if (_ioHelper.PathStartsWith(path, _rootPath, Path.DirectorySeparatorChar)) { // this says that 4.7.2 supports long paths - but Windows does not // https://docs.microsoft.com/en-us/dotnet/api/system.io.pathtoolongexception?view=netframework-4.7.2 diff --git a/src/Umbraco.Core/IO/ShadowWrapper.cs b/src/Umbraco.Core/IO/ShadowWrapper.cs index 44152d7c1a..641e3845b6 100644 --- a/src/Umbraco.Core/IO/ShadowWrapper.cs +++ b/src/Umbraco.Core/IO/ShadowWrapper.cs @@ -12,14 +12,16 @@ namespace Umbraco.Core.IO private readonly Func _isScoped; private readonly IFileSystem _innerFileSystem; + private readonly IIOHelper _ioHelper; private readonly string _shadowPath; private ShadowFileSystem _shadowFileSystem; private string _shadowDir; - public ShadowWrapper(IFileSystem innerFileSystem, string shadowPath, Func isScoped = null) + public ShadowWrapper(IFileSystem innerFileSystem, string shadowPath, IIOHelper ioHelper, Func isScoped = null) { _innerFileSystem = innerFileSystem; _shadowPath = shadowPath; + _ioHelper = ioHelper; _isScoped = isScoped; } @@ -33,12 +35,14 @@ namespace Umbraco.Core.IO // we should end up with a unique identifier eventually - but just // detect infinite loops (just in case) + var ioHelper = Current.Factory.GetInstance(); + for (var i = 0; i < retries; i++) { var id = GuidUtils.ToBase32String(Guid.NewGuid(), idLength); var virt = ShadowFsPath + "/" + id; - var shadowDir = Current.IOHelper.MapPath(virt); + var shadowDir = ioHelper.MapPath(virt); if (Directory.Exists(shadowDir)) continue; @@ -56,9 +60,9 @@ namespace Umbraco.Core.IO // in a single thread anyways var virt = ShadowFsPath + "/" + id + "/" + _shadowPath; - _shadowDir = Current.IOHelper.MapPath(virt); + _shadowDir = _ioHelper.MapPath(virt); Directory.CreateDirectory(_shadowDir); - var tempfs = new PhysicalFileSystem(virt); + var tempfs = new PhysicalFileSystem(virt, _ioHelper); _shadowFileSystem = new ShadowFileSystem(_innerFileSystem, tempfs); } @@ -83,7 +87,7 @@ namespace Umbraco.Core.IO // shadowPath make be path/to/dir, remove each dir = dir.Replace("/", "\\"); - var min = Current.IOHelper.MapPath(ShadowFsPath).Length; + var min = _ioHelper.MapPath(ShadowFsPath).Length; var pos = dir.LastIndexOf("\\", StringComparison.OrdinalIgnoreCase); while (pos > min) { diff --git a/src/Umbraco.Core/IO/SystemDirectories.cs b/src/Umbraco.Core/IO/SystemDirectories.cs index c5c410ff3f..d6c9e961b9 100644 --- a/src/Umbraco.Core/IO/SystemDirectories.cs +++ b/src/Umbraco.Core/IO/SystemDirectories.cs @@ -6,6 +6,8 @@ namespace Umbraco.Core.IO //all paths has a starting but no trailing / public class SystemDirectories { + private static IIOHelper IOHelper => Current.Factory.GetInstance(); + public static string Bin => "~/bin"; public static string Config => "~/config"; @@ -30,13 +32,13 @@ namespace Umbraco.Core.IO public static string MacroPartials => MvcViews + "/MacroPartials/"; - public static string Media => Current.IOHelper.ReturnPath("umbracoMediaPath", "~/media"); + public static string Media => IOHelper.ReturnPath("umbracoMediaPath", "~/media"); - public static string Scripts => Current.IOHelper.ReturnPath("umbracoScriptsPath", "~/scripts"); + public static string Scripts => IOHelper.ReturnPath("umbracoScriptsPath", "~/scripts"); - public static string Css => Current.IOHelper.ReturnPath("umbracoCssPath", "~/css"); + public static string Css => IOHelper.ReturnPath("umbracoCssPath", "~/css"); - public static string Umbraco => Current.IOHelper.ReturnPath("umbracoPath", "~/umbraco"); + public static string Umbraco => IOHelper.ReturnPath("umbracoPath", "~/umbraco"); public static string Packages => Data + "/packages"; diff --git a/src/Umbraco.Core/Logging/Viewer/JsonLogViewer.cs b/src/Umbraco.Core/Logging/Viewer/JsonLogViewer.cs index bbe2f3704d..aea1c8fae4 100644 --- a/src/Umbraco.Core/Logging/Viewer/JsonLogViewer.cs +++ b/src/Umbraco.Core/Logging/Viewer/JsonLogViewer.cs @@ -5,6 +5,7 @@ using System.Linq; using Newtonsoft.Json; using Serilog.Events; using Serilog.Formatting.Compact.Reader; +using Umbraco.Core.IO; namespace Umbraco.Core.Logging.Viewer { @@ -13,7 +14,7 @@ namespace Umbraco.Core.Logging.Viewer private readonly string _logsPath; private readonly ILogger _logger; - public JsonLogViewer(ILogger logger, string logsPath = "", string searchPath = "") : base(searchPath) + public JsonLogViewer(ILogger logger, IIOHelper ioHelper, string logsPath = "", string searchPath = "") : base(ioHelper, searchPath) { if (string.IsNullOrEmpty(logsPath)) logsPath = $@"{AppDomain.CurrentDomain.BaseDirectory}\App_Data\Logs\"; diff --git a/src/Umbraco.Core/Logging/Viewer/LogViewerComposer.cs b/src/Umbraco.Core/Logging/Viewer/LogViewerComposer.cs index 8eb835b4d9..f92ca0140a 100644 --- a/src/Umbraco.Core/Logging/Viewer/LogViewerComposer.cs +++ b/src/Umbraco.Core/Logging/Viewer/LogViewerComposer.cs @@ -1,5 +1,6 @@ using Umbraco.Core.Compose; using Umbraco.Core.Composing; +using Umbraco.Core.IO; namespace Umbraco.Core.Logging.Viewer { @@ -9,7 +10,7 @@ namespace Umbraco.Core.Logging.Viewer { public void Compose(Composition composition) { - composition.SetLogViewer(_ => new JsonLogViewer(composition.Logger)); + composition.SetLogViewer(factory => new JsonLogViewer(composition.Logger, factory.GetInstance())); } } } diff --git a/src/Umbraco.Core/Logging/Viewer/LogViewerSourceBase.cs b/src/Umbraco.Core/Logging/Viewer/LogViewerSourceBase.cs index c2d9dbb46c..4cc70eaf42 100644 --- a/src/Umbraco.Core/Logging/Viewer/LogViewerSourceBase.cs +++ b/src/Umbraco.Core/Logging/Viewer/LogViewerSourceBase.cs @@ -15,17 +15,19 @@ namespace Umbraco.Core.Logging.Viewer { public abstract class LogViewerSourceBase : ILogViewer { - protected LogViewerSourceBase(string pathToSearches = "") + private readonly string _searchesConfigPath; + private readonly IIOHelper _ioHelper; + + protected LogViewerSourceBase(IIOHelper ioHelper, string pathToSearches = "") { if (string.IsNullOrEmpty(pathToSearches)) // ReSharper disable once StringLiteralTypo - pathToSearches = Current.IOHelper.MapPath("~/Config/logviewer.searches.config.js"); + pathToSearches = ioHelper.MapPath("~/Config/logviewer.searches.config.js"); _searchesConfigPath = pathToSearches; + _ioHelper = ioHelper; } - private readonly string _searchesConfigPath; - public abstract bool CanHandleLargeLogs { get; } /// @@ -40,7 +42,7 @@ namespace Umbraco.Core.Logging.Viewer //Our default implementation //If file does not exist - lets create it with an empty array - EnsureFileExists(_searchesConfigPath, "[]"); + EnsureFileExists(_searchesConfigPath, "[]", _ioHelper); var rawJson = System.IO.File.ReadAllText(_searchesConfigPath); return JsonConvert.DeserializeObject(rawJson); @@ -58,7 +60,7 @@ namespace Umbraco.Core.Logging.Viewer var rawJson = JsonConvert.SerializeObject(searches, Formatting.Indented); //If file does not exist - lets create it with an empty array - EnsureFileExists(_searchesConfigPath, "[]"); + EnsureFileExists(_searchesConfigPath, "[]", _ioHelper); //Write it back down to file System.IO.File.WriteAllText(_searchesConfigPath, rawJson); @@ -180,9 +182,9 @@ namespace Umbraco.Core.Logging.Viewer }; } - private static void EnsureFileExists(string path, string contents) + private static void EnsureFileExists(string path, string contents, IIOHelper ioHelper) { - var absolutePath = Current.IOHelper.MapPath(path); + var absolutePath = ioHelper.MapPath(path); if (System.IO.File.Exists(absolutePath)) return; using (var writer = System.IO.File.CreateText(absolutePath)) diff --git a/src/Umbraco.Core/Manifest/ManifestParser.cs b/src/Umbraco.Core/Manifest/ManifestParser.cs index cac904a520..9a34735987 100644 --- a/src/Umbraco.Core/Manifest/ManifestParser.cs +++ b/src/Umbraco.Core/Manifest/ManifestParser.cs @@ -22,6 +22,7 @@ namespace Umbraco.Core.Manifest private readonly IAppPolicyCache _cache; private readonly ILogger _logger; + private readonly IIOHelper _ioHelper; private readonly ManifestValueValidatorCollection _validators; private readonly ManifestFilterCollection _filters; @@ -30,14 +31,14 @@ namespace Umbraco.Core.Manifest /// /// Initializes a new instance of the class. /// - public ManifestParser(AppCaches appCaches, ManifestValueValidatorCollection validators, ManifestFilterCollection filters, ILogger logger) - : this(appCaches, validators, filters, "~/App_Plugins", logger) + public ManifestParser(AppCaches appCaches, ManifestValueValidatorCollection validators, ManifestFilterCollection filters, ILogger logger, IIOHelper ioHelper) + : this(appCaches, validators, filters, "~/App_Plugins", logger, ioHelper) { } /// /// Initializes a new instance of the class. /// - private ManifestParser(AppCaches appCaches, ManifestValueValidatorCollection validators, ManifestFilterCollection filters, string path, ILogger logger) + private ManifestParser(AppCaches appCaches, ManifestValueValidatorCollection validators, ManifestFilterCollection filters, string path, ILogger logger, IIOHelper ioHelper) { if (appCaches == null) throw new ArgumentNullException(nameof(appCaches)); _cache = appCaches.RuntimeCache; @@ -46,12 +47,13 @@ namespace Umbraco.Core.Manifest if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullOrEmptyException(nameof(path)); Path = path; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _ioHelper = ioHelper; } public string Path { get => _path; - set => _path = value.StartsWith("~/") ? Current.IOHelper.MapPath(value) : value; + set => _path = value.StartsWith("~/") ? _ioHelper.MapPath(value) : value; } /// @@ -166,9 +168,9 @@ namespace Umbraco.Core.Manifest // scripts and stylesheets are raw string, must process here for (var i = 0; i < manifest.Scripts.Length; i++) - manifest.Scripts[i] = Current.IOHelper.ResolveVirtualUrl(manifest.Scripts[i]); + manifest.Scripts[i] = _ioHelper.ResolveVirtualUrl(manifest.Scripts[i]); for (var i = 0; i < manifest.Stylesheets.Length; i++) - manifest.Stylesheets[i] = Current.IOHelper.ResolveVirtualUrl(manifest.Stylesheets[i]); + manifest.Stylesheets[i] = _ioHelper.ResolveVirtualUrl(manifest.Stylesheets[i]); // add property editors that are also parameter editors, to the parameter editors list // (the manifest format is kinda legacy) diff --git a/src/Umbraco.Core/Migrations/Install/DatabaseBuilder.cs b/src/Umbraco.Core/Migrations/Install/DatabaseBuilder.cs index a0c87ce510..5d0e3246fc 100644 --- a/src/Umbraco.Core/Migrations/Install/DatabaseBuilder.cs +++ b/src/Umbraco.Core/Migrations/Install/DatabaseBuilder.cs @@ -29,13 +29,14 @@ namespace Umbraco.Core.Migrations.Install private readonly IMigrationBuilder _migrationBuilder; private readonly IKeyValueService _keyValueService; private readonly ILogger _logger; + private readonly IIOHelper _ioHelper; private DatabaseSchemaResult _databaseSchemaValidationResult; /// /// Initializes a new instance of the class. /// - public DatabaseBuilder(IScopeProvider scopeProvider, IGlobalSettings globalSettings, IUmbracoDatabaseFactory databaseFactory, IRuntimeState runtime, ILogger logger, IMigrationBuilder migrationBuilder, IKeyValueService keyValueService) + public DatabaseBuilder(IScopeProvider scopeProvider, IGlobalSettings globalSettings, IUmbracoDatabaseFactory databaseFactory, IRuntimeState runtime, ILogger logger, IMigrationBuilder migrationBuilder, IKeyValueService keyValueService, IIOHelper ioHelper) { _scopeProvider = scopeProvider; _globalSettings = globalSettings; @@ -44,6 +45,7 @@ namespace Umbraco.Core.Migrations.Install _logger = logger; _migrationBuilder = migrationBuilder; _keyValueService = keyValueService; + _ioHelper = ioHelper; } #region Status @@ -125,14 +127,14 @@ namespace Umbraco.Core.Migrations.Install /// public void ConfigureEmbeddedDatabaseConnection() { - ConfigureEmbeddedDatabaseConnection(_databaseFactory, _logger); + ConfigureEmbeddedDatabaseConnection(_databaseFactory, _ioHelper, _logger); } - private static void ConfigureEmbeddedDatabaseConnection(IUmbracoDatabaseFactory factory, ILogger logger) + private static void ConfigureEmbeddedDatabaseConnection(IUmbracoDatabaseFactory factory, IIOHelper ioHelper, ILogger logger) { - SaveConnectionString(EmbeddedDatabaseConnectionString, Constants.DbProviderNames.SqlCe, logger); + SaveConnectionString(EmbeddedDatabaseConnectionString, Constants.DbProviderNames.SqlCe, ioHelper, logger); - var path = Path.Combine(Current.IOHelper.GetRootDirectorySafe(), "App_Data", "Umbraco.sdf"); + var path = Path.Combine(ioHelper.GetRootDirectorySafe(), "App_Data", "Umbraco.sdf"); if (File.Exists(path) == false) { // this should probably be in a "using (new SqlCeEngine)" clause but not sure @@ -154,7 +156,7 @@ namespace Umbraco.Core.Migrations.Install { const string providerName = Constants.DbProviderNames.SqlServer; - SaveConnectionString(connectionString, providerName, _logger); + SaveConnectionString(connectionString, providerName, _ioHelper, _logger); _databaseFactory.Configure(connectionString, providerName); } @@ -170,7 +172,7 @@ namespace Umbraco.Core.Migrations.Install { var connectionString = GetDatabaseConnectionString(server, databaseName, user, password, databaseProvider, out var providerName); - SaveConnectionString(connectionString, providerName, _logger); + SaveConnectionString(connectionString, providerName, _ioHelper, _logger); _databaseFactory.Configure(connectionString, providerName); } @@ -201,7 +203,7 @@ namespace Umbraco.Core.Migrations.Install public void ConfigureIntegratedSecurityDatabaseConnection(string server, string databaseName) { var connectionString = GetIntegratedSecurityDatabaseConnectionString(server, databaseName); - SaveConnectionString(connectionString, Constants.DbProviderNames.SqlServer, _logger); + SaveConnectionString(connectionString, Constants.DbProviderNames.SqlServer, _ioHelper, _logger); _databaseFactory.Configure(connectionString, Constants.DbProviderNames.SqlServer); } @@ -277,13 +279,13 @@ namespace Umbraco.Core.Migrations.Install /// The connection string. /// The provider name. /// A logger. - private static void SaveConnectionString(string connectionString, string providerName, ILogger logger) + private static void SaveConnectionString(string connectionString, string providerName, IIOHelper ioHelper, ILogger logger) { if (string.IsNullOrWhiteSpace(connectionString)) throw new ArgumentNullOrEmptyException(nameof(connectionString)); if (string.IsNullOrWhiteSpace(providerName)) throw new ArgumentNullOrEmptyException(nameof(providerName)); var fileSource = "web.config"; - var fileName = Current.IOHelper.MapPath(SystemDirectories.Root +"/" + fileSource); + var fileName = ioHelper.MapPath(SystemDirectories.Root +"/" + fileSource); var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); if (xml.Root == null) throw new Exception($"Invalid {fileSource} file (no root)."); @@ -296,7 +298,7 @@ namespace Umbraco.Core.Migrations.Install if (configSourceAttribute != null) { fileSource = configSourceAttribute.Value; - fileName = Current.IOHelper.MapPath(SystemDirectories.Root + "/" + fileSource); + fileName = ioHelper.MapPath(SystemDirectories.Root + "/" + fileSource); if (!File.Exists(fileName)) throw new Exception($"Invalid configSource \"{fileSource}\" (no such file)."); diff --git a/src/Umbraco.Core/Packaging/PackageFileInstallation.cs b/src/Umbraco.Core/Packaging/PackageFileInstallation.cs index 45e40b8e5f..01bb316612 100644 --- a/src/Umbraco.Core/Packaging/PackageFileInstallation.cs +++ b/src/Umbraco.Core/Packaging/PackageFileInstallation.cs @@ -20,12 +20,14 @@ namespace Umbraco.Core.Packaging internal class PackageFileInstallation { private readonly CompiledPackageXmlParser _parser; + private readonly IIOHelper _ioHelper; private readonly IProfilingLogger _logger; private readonly PackageExtraction _packageExtraction; - public PackageFileInstallation(CompiledPackageXmlParser parser, IProfilingLogger logger) + public PackageFileInstallation(CompiledPackageXmlParser parser, IIOHelper ioHelper, IProfilingLogger logger) { _parser = parser; + _ioHelper = ioHelper; _logger = logger; _packageExtraction = new PackageExtraction(); } @@ -60,15 +62,15 @@ namespace Umbraco.Core.Packaging foreach (var item in package.Files.ToArray()) { - removedFiles.Add(Current.IOHelper.GetRelativePath(item)); + removedFiles.Add(_ioHelper.GetRelativePath(item)); //here we need to try to find the file in question as most packages does not support the tilde char - var file = Current.IOHelper.FindFile(item); + var file = _ioHelper.FindFile(item); if (file != null) { // TODO: Surely this should be ~/ ? file = file.EnsureStartsWith("/"); - var filePath = Current.IOHelper.MapPath(file); + var filePath = _ioHelper.MapPath(file); if (File.Exists(filePath)) File.Delete(filePath); diff --git a/src/Umbraco.Core/Packaging/PackagesRepository.cs b/src/Umbraco.Core/Packaging/PackagesRepository.cs index 458a239cc0..7ae3462b87 100644 --- a/src/Umbraco.Core/Packaging/PackagesRepository.cs +++ b/src/Umbraco.Core/Packaging/PackagesRepository.cs @@ -29,6 +29,7 @@ namespace Umbraco.Core.Packaging private readonly ILocalizationService _languageService; private readonly IEntityXmlSerializer _serializer; private readonly ILogger _logger; + private readonly IIOHelper _ioHelper; private readonly string _packageRepositoryFileName; private readonly string _mediaFolderPath; private readonly string _packagesFolderPath; @@ -44,6 +45,7 @@ namespace Umbraco.Core.Packaging /// /// /// + /// /// /// /// @@ -55,6 +57,7 @@ namespace Umbraco.Core.Packaging public PackagesRepository(IContentService contentService, IContentTypeService contentTypeService, IDataTypeService dataTypeService, IFileService fileService, IMacroService macroService, ILocalizationService languageService, + IIOHelper ioHelper, IEntityXmlSerializer serializer, ILogger logger, string packageRepositoryFileName, string tempFolderPath = null, string packagesFolderPath = null, string mediaFolderPath = null) @@ -68,6 +71,7 @@ namespace Umbraco.Core.Packaging _languageService = languageService; _serializer = serializer; _logger = logger; + _ioHelper = ioHelper; _packageRepositoryFileName = packageRepositoryFileName; _tempFolderPath = tempFolderPath ?? SystemDirectories.TempData.EnsureEndsWith('/') + "PackageFiles"; @@ -155,7 +159,7 @@ namespace Umbraco.Core.Packaging ValidatePackage(definition); //Create a folder for building this package - var temporaryPath = Current.IOHelper.MapPath(_tempFolderPath.EnsureEndsWith('/') + Guid.NewGuid()); + var temporaryPath = _ioHelper.MapPath(_tempFolderPath.EnsureEndsWith('/') + Guid.NewGuid()); if (Directory.Exists(temporaryPath) == false) Directory.CreateDirectory(temporaryPath); @@ -178,13 +182,13 @@ namespace Umbraco.Core.Packaging //Files foreach (var fileName in definition.Files) - AppendFileToPackage(fileName, temporaryPath, filesXml); + AppendFileToPackage(fileName, temporaryPath, filesXml, _ioHelper); //Load view on install... if (!string.IsNullOrEmpty(definition.PackageView)) { var control = new XElement("view", definition.PackageView); - AppendFileToPackage(definition.PackageView, temporaryPath, filesXml); + AppendFileToPackage(definition.PackageView, temporaryPath, filesXml, _ioHelper); root.Add(control); } @@ -214,11 +218,11 @@ namespace Umbraco.Core.Packaging // check if there's a packages directory below media - if (Directory.Exists(Current.IOHelper.MapPath(_mediaFolderPath)) == false) - Directory.CreateDirectory(Current.IOHelper.MapPath(_mediaFolderPath)); + if (Directory.Exists(_ioHelper.MapPath(_mediaFolderPath)) == false) + Directory.CreateDirectory(_ioHelper.MapPath(_mediaFolderPath)); var packPath = _mediaFolderPath.EnsureEndsWith('/') + (definition.Name + "_" + definition.Version).Replace(' ', '_') + ".zip"; - ZipPackage(temporaryPath, Current.IOHelper.MapPath(packPath)); + ZipPackage(temporaryPath, _ioHelper.MapPath(packPath)); //we need to update the package path and save it definition.PackagePath = packPath; @@ -294,7 +298,7 @@ namespace Umbraco.Core.Packaging macros.Add(macroXml); //if the macro has a file copy it to the xml if (!string.IsNullOrEmpty(macro.MacroSource)) - AppendFileToPackage(macro.MacroSource, temporaryPath, filesXml); + AppendFileToPackage(macro.MacroSource, temporaryPath, filesXml,_ioHelper); } root.Add(macros); } @@ -444,12 +448,12 @@ namespace Umbraco.Core.Packaging /// The path. /// The package directory. /// The files xml node - private static void AppendFileToPackage(string path, string packageDirectory, XContainer filesXml) + private static void AppendFileToPackage(string path, string packageDirectory, XContainer filesXml, IIOHelper ioHelper) { if (!path.StartsWith("~/") && !path.StartsWith("/")) path = "~/" + path; - var serverPath = Current.IOHelper.MapPath(path); + var serverPath = ioHelper.MapPath(path); if (File.Exists(serverPath)) AppendFileXml(new FileInfo(serverPath), path, packageDirectory, filesXml); @@ -608,11 +612,11 @@ namespace Umbraco.Core.Packaging private XDocument EnsureStorage(out string packagesFile) { - var packagesFolder = Current.IOHelper.MapPath(_packagesFolderPath); + var packagesFolder = _ioHelper.MapPath(_packagesFolderPath); //ensure it exists Directory.CreateDirectory(packagesFolder); - packagesFile = Current.IOHelper.MapPath(CreatedPackagesFile); + packagesFile = _ioHelper.MapPath(CreatedPackagesFile); if (!File.Exists(packagesFile)) { var xml = new XDocument(new XElement("packages")); diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/PartialViewMacroRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/PartialViewMacroRepository.cs index d707bcee10..03de23004e 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/PartialViewMacroRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/PartialViewMacroRepository.cs @@ -5,8 +5,8 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { internal class PartialViewMacroRepository : PartialViewRepository, IPartialViewMacroRepository { - public PartialViewMacroRepository(IFileSystems fileSystems) - : base(fileSystems.MacroPartialsFileSystem) + public PartialViewMacroRepository(IFileSystems fileSystems, IIOHelper ioHelper) + : base(fileSystems.MacroPartialsFileSystem, ioHelper) { } protected override PartialViewType ViewType => PartialViewType.PartialViewMacro; diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/PartialViewRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/PartialViewRepository.cs index d7d1be55c7..1d5cd15ce8 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/PartialViewRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/PartialViewRepository.cs @@ -10,13 +10,19 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { internal class PartialViewRepository : FileRepository, IPartialViewRepository { - public PartialViewRepository(IFileSystems fileSystems) - : base(fileSystems.PartialViewsFileSystem) - { } + private readonly IIOHelper _ioHelper; - protected PartialViewRepository(IFileSystem fileSystem) + public PartialViewRepository(IFileSystems fileSystems, IIOHelper ioHelper) + : base(fileSystems.PartialViewsFileSystem) + { + _ioHelper = ioHelper; + } + + protected PartialViewRepository(IFileSystem fileSystem, IIOHelper ioHelper) : base(fileSystem) - { } + { + _ioHelper = ioHelper; + } protected virtual PartialViewType ViewType => PartialViewType.PartialView; @@ -104,8 +110,8 @@ namespace Umbraco.Core.Persistence.Repositories.Implement // validate path & extension var validDir = SystemDirectories.MvcViews; - var isValidPath = Current.IOHelper.VerifyEditPath(fullPath, validDir); - var isValidExtension = Current.IOHelper.VerifyFileExtension(fullPath, ValidExtensions); + var isValidPath = _ioHelper.VerifyEditPath(fullPath, validDir); + var isValidExtension = _ioHelper.VerifyFileExtension(fullPath, ValidExtensions); return isValidPath && isValidExtension; } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/TemplateRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/TemplateRepository.cs index 5fd319e4d4..3d1d7aa786 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/TemplateRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/TemplateRepository.cs @@ -23,12 +23,14 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// internal class TemplateRepository : NPocoRepositoryBase, ITemplateRepository { + private readonly IIOHelper _ioHelper; private readonly IFileSystem _viewsFileSystem; private readonly ViewHelper _viewHelper; - public TemplateRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger, IFileSystems fileSystems) + public TemplateRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger, IFileSystems fileSystems, IIOHelper ioHelper) : base(scopeAccessor, cache, logger) { + _ioHelper = ioHelper; _viewsFileSystem = fileSystems.MvcViewsFileSystem; _viewHelper = new ViewHelper(_viewsFileSystem); } @@ -593,8 +595,8 @@ namespace Umbraco.Core.Persistence.Repositories.Implement validExts.Add("vbhtml"); // validate path and extension - var validFile = Current.IOHelper.VerifyEditPath(path, validDirs); - var validExtension = Current.IOHelper.VerifyFileExtension(path, validExts); + var validFile = _ioHelper.VerifyEditPath(path, validDirs); + var validExtension = _ioHelper.VerifyFileExtension(path, validExts); return validFile && validExtension; } diff --git a/src/Umbraco.Core/PropertyEditors/ConfigurationField.cs b/src/Umbraco.Core/PropertyEditors/ConfigurationField.cs index ee07f8dcef..bf692d1c98 100644 --- a/src/Umbraco.Core/PropertyEditors/ConfigurationField.cs +++ b/src/Umbraco.Core/PropertyEditors/ConfigurationField.cs @@ -94,7 +94,7 @@ namespace Umbraco.Core.PropertyEditors public string View { get => _view; - set => _view = Current.IOHelper.ResolveVirtualUrl(value); + set => _view = Current.Factory.GetInstance().ResolveVirtualUrl(value); } /// diff --git a/src/Umbraco.Core/PropertyEditors/GridEditor.cs b/src/Umbraco.Core/PropertyEditors/GridEditor.cs index 388e79675c..869e427e49 100644 --- a/src/Umbraco.Core/PropertyEditors/GridEditor.cs +++ b/src/Umbraco.Core/PropertyEditors/GridEditor.cs @@ -8,11 +8,13 @@ namespace Umbraco.Core.PropertyEditors { public class GridEditor : IGridEditorConfig { + private readonly IIOHelper _ioHelper; private string _view; private string _render; - public GridEditor() + public GridEditor(IIOHelper ioHelper) { + _ioHelper = ioHelper; Config = new Dictionary(); } @@ -29,14 +31,14 @@ namespace Umbraco.Core.PropertyEditors public string View { get => _view; - set => _view = Current.IOHelper.ResolveVirtualUrl(value); + set => _view = _ioHelper.ResolveVirtualUrl(value); } [JsonProperty("render")] public string Render { get => _render; - set => _render = Current.IOHelper.ResolveVirtualUrl(value); + set => _render = _ioHelper.ResolveVirtualUrl(value); } [JsonProperty("icon", Required = Required.Always)] diff --git a/src/Umbraco.Core/Runtime/CoreInitialComponent.cs b/src/Umbraco.Core/Runtime/CoreInitialComponent.cs index f88417948b..e90ad41155 100644 --- a/src/Umbraco.Core/Runtime/CoreInitialComponent.cs +++ b/src/Umbraco.Core/Runtime/CoreInitialComponent.cs @@ -5,15 +5,22 @@ namespace Umbraco.Core.Runtime { public class CoreInitialComponent : IComponent { + private readonly IIOHelper _ioHelper; + + public CoreInitialComponent(IIOHelper ioHelper) + { + _ioHelper = ioHelper; + } + public void Initialize() { // ensure we have some essential directories // every other component can then initialize safely - Current.IOHelper.EnsurePathExists("~/App_Data"); - Current.IOHelper.EnsurePathExists(SystemDirectories.Media); - Current.IOHelper.EnsurePathExists(SystemDirectories.MvcViews); - Current.IOHelper.EnsurePathExists(SystemDirectories.MvcViews + "/Partials"); - Current.IOHelper.EnsurePathExists(SystemDirectories.MvcViews + "/MacroPartials"); + _ioHelper.EnsurePathExists("~/App_Data"); + _ioHelper.EnsurePathExists(SystemDirectories.Media); + _ioHelper.EnsurePathExists(SystemDirectories.MvcViews); + _ioHelper.EnsurePathExists(SystemDirectories.MvcViews + "/Partials"); + _ioHelper.EnsurePathExists(SystemDirectories.MvcViews + "/MacroPartials"); } public void Terminate() diff --git a/src/Umbraco.Core/Runtime/CoreRuntime.cs b/src/Umbraco.Core/Runtime/CoreRuntime.cs index 90dbbe666c..efecb539cb 100644 --- a/src/Umbraco.Core/Runtime/CoreRuntime.cs +++ b/src/Umbraco.Core/Runtime/CoreRuntime.cs @@ -239,7 +239,7 @@ namespace Umbraco.Core.Runtime { var path = GetApplicationRootPath(); if (string.IsNullOrWhiteSpace(path) == false) - Current.IOHelper.SetRootDirectory(path); + IOHelper.SetRootDirectory(path); } private bool AcquireMainDom(MainDom mainDom) diff --git a/src/Umbraco.Core/Services/Implement/FileService.cs b/src/Umbraco.Core/Services/Implement/FileService.cs index cde8ed30fe..00a95fced6 100644 --- a/src/Umbraco.Core/Services/Implement/FileService.cs +++ b/src/Umbraco.Core/Services/Implement/FileService.cs @@ -19,6 +19,7 @@ namespace Umbraco.Core.Services.Implement /// public class FileService : ScopeRepositoryService, IFileService { + private readonly IIOHelper _ioHelper; private readonly IStylesheetRepository _stylesheetRepository; private readonly IScriptRepository _scriptRepository; private readonly ITemplateRepository _templateRepository; @@ -29,12 +30,13 @@ namespace Umbraco.Core.Services.Implement private const string PartialViewHeader = "@inherits Umbraco.Web.Mvc.UmbracoViewPage"; private const string PartialViewMacroHeader = "@inherits Umbraco.Web.Macros.PartialViewMacroPage"; - public FileService(IScopeProvider uowProvider, ILogger logger, IEventMessagesFactory eventMessagesFactory, + public FileService(IScopeProvider uowProvider, IIOHelper ioHelper, ILogger logger, IEventMessagesFactory eventMessagesFactory, IStylesheetRepository stylesheetRepository, IScriptRepository scriptRepository, ITemplateRepository templateRepository, IPartialViewRepository partialViewRepository, IPartialViewMacroRepository partialViewMacroRepository, IAuditRepository auditRepository) : base(uowProvider, logger, eventMessagesFactory) { + _ioHelper = ioHelper; _stylesheetRepository = stylesheetRepository; _scriptRepository = scriptRepository; _templateRepository = templateRepository; @@ -664,7 +666,7 @@ namespace Umbraco.Core.Services.Implement public IEnumerable GetPartialViewSnippetNames(params string[] filterNames) { - var snippetPath = Current.IOHelper.MapPath($"{SystemDirectories.Umbraco}/PartialViewMacros/Templates/"); + var snippetPath = _ioHelper.MapPath($"{SystemDirectories.Umbraco}/PartialViewMacros/Templates/"); var files = Directory.GetFiles(snippetPath, "*.cshtml") .Select(Path.GetFileNameWithoutExtension) .Except(filterNames, StringComparer.InvariantCultureIgnoreCase) @@ -898,7 +900,7 @@ namespace Umbraco.Core.Services.Implement fileName += ".cshtml"; } - var snippetPath = Current.IOHelper.MapPath($"{SystemDirectories.Umbraco}/PartialViewMacros/Templates/{fileName}"); + var snippetPath = _ioHelper.MapPath($"{SystemDirectories.Umbraco}/PartialViewMacros/Templates/{fileName}"); return System.IO.File.Exists(snippetPath) ? Attempt.Succeed(snippetPath) : Attempt.Fail(); diff --git a/src/Umbraco.Core/Services/Implement/NotificationService.cs b/src/Umbraco.Core/Services/Implement/NotificationService.cs index 65040f625a..3a42e576de 100644 --- a/src/Umbraco.Core/Services/Implement/NotificationService.cs +++ b/src/Umbraco.Core/Services/Implement/NotificationService.cs @@ -30,9 +30,10 @@ namespace Umbraco.Core.Services.Implement private readonly IGlobalSettings _globalSettings; private readonly IContentSection _contentSection; private readonly ILogger _logger; + private readonly IIOHelper _ioHelper; public NotificationService(IScopeProvider provider, IUserService userService, IContentService contentService, ILocalizationService localizationService, - ILogger logger, INotificationsRepository notificationsRepository, IGlobalSettings globalSettings, IContentSection contentSection) + ILogger logger, IIOHelper ioHelper, INotificationsRepository notificationsRepository, IGlobalSettings globalSettings, IContentSection contentSection) { _notificationsRepository = notificationsRepository; _globalSettings = globalSettings; @@ -42,6 +43,7 @@ namespace Umbraco.Core.Services.Implement _contentService = contentService ?? throw new ArgumentNullException(nameof(contentService)); _localizationService = localizationService; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _ioHelper = ioHelper; } /// @@ -384,7 +386,7 @@ namespace Umbraco.Core.Services.Implement var protocol = _globalSettings.UseHttps ? "https" : "http"; var subjectVars = new NotificationEmailSubjectParams( - string.Concat(siteUri.Authority, Current.IOHelper.ResolveUrl(SystemDirectories.Umbraco)), + string.Concat(siteUri.Authority, _ioHelper.ResolveUrl(SystemDirectories.Umbraco)), actionName, content.Name); @@ -400,7 +402,7 @@ namespace Umbraco.Core.Services.Implement string.Concat(content.Id, ".aspx"), protocol), performingUser.Name, - string.Concat(siteUri.Authority, Current.IOHelper.ResolveUrl(SystemDirectories.Umbraco)), + string.Concat(siteUri.Authority, _ioHelper.ResolveUrl(SystemDirectories.Umbraco)), summary.ToString()); // create the mail message diff --git a/src/Umbraco.Core/Services/Implement/PackagingService.cs b/src/Umbraco.Core/Services/Implement/PackagingService.cs index c0946e4468..3636705f8b 100644 --- a/src/Umbraco.Core/Services/Implement/PackagingService.cs +++ b/src/Umbraco.Core/Services/Implement/PackagingService.cs @@ -23,6 +23,7 @@ namespace Umbraco.Core.Services.Implement { private readonly IPackageInstallation _packageInstallation; + private readonly IIOHelper _ioHelper; private readonly IAuditService _auditService; private readonly ICreatedPackagesRepository _createdPackages; private readonly IInstalledPackagesRepository _installedPackages; @@ -32,12 +33,14 @@ namespace Umbraco.Core.Services.Implement IAuditService auditService, ICreatedPackagesRepository createdPackages, IInstalledPackagesRepository installedPackages, - IPackageInstallation packageInstallation) + IPackageInstallation packageInstallation, + IIOHelper ioHelper) { _auditService = auditService; _createdPackages = createdPackages; _installedPackages = installedPackages; _packageInstallation = packageInstallation; + _ioHelper = ioHelper; } #region Package Files @@ -64,7 +67,7 @@ namespace Umbraco.Core.Services.Implement //successful if (bytes.Length > 0) { - var packagePath = Current.IOHelper.MapPath(SystemDirectories.Packages); + var packagePath = _ioHelper.MapPath(SystemDirectories.Packages); // Check for package directory if (Directory.Exists(packagePath) == false) diff --git a/src/Umbraco.Core/StringExtensions.cs b/src/Umbraco.Core/StringExtensions.cs index 027b5fc928..854a96a51f 100644 --- a/src/Umbraco.Core/StringExtensions.cs +++ b/src/Umbraco.Core/StringExtensions.cs @@ -112,7 +112,9 @@ namespace Umbraco.Core if (isValid) { - var resolvedUrlResult = Current.IOHelper.TryResolveUrl(input); + var ioHelper = Current.Factory.GetInstance(); + + var resolvedUrlResult = ioHelper.TryResolveUrl(input); //if the resolution was success, return it, otherwise just return the path, we've detected // it's a path but maybe it's relative and resolution has failed, etc... in which case we're just // returning what was given to us. diff --git a/src/Umbraco.Core/UriExtensions.cs b/src/Umbraco.Core/UriExtensions.cs index 9fd1bf46dc..97c350f0b4 100644 --- a/src/Umbraco.Core/UriExtensions.cs +++ b/src/Umbraco.Core/UriExtensions.cs @@ -114,8 +114,10 @@ namespace Umbraco.Core .TrimStart(authority) .TrimStart("/"); + var ioHelper = Current.Factory.GetInstance(); + //check if this is in the umbraco back office - return afterAuthority.InvariantStartsWith(Current.IOHelper.ResolveUrl("~/install").TrimStart("/")); + return afterAuthority.InvariantStartsWith(ioHelper.ResolveUrl("~/install").TrimStart("/")); } /// diff --git a/src/Umbraco.Tests/Components/ComponentTests.cs b/src/Umbraco.Tests/Components/ComponentTests.cs index 5a437e402f..365a10224b 100644 --- a/src/Umbraco.Tests/Components/ComponentTests.cs +++ b/src/Umbraco.Tests/Components/ComponentTests.cs @@ -32,9 +32,10 @@ namespace Umbraco.Tests.Components var mock = new Mock(); var logger = Mock.Of(); + var ioHelper = Mock.Of(); var typeFinder = new TypeFinder(logger); var f = new UmbracoDatabaseFactory(logger, new Lazy(() => new MapperCollection(Enumerable.Empty()))); - var fs = new FileSystems(mock.Object, logger); + var fs = new FileSystems(mock.Object, logger, ioHelper); var p = new ScopeProvider(f, fs, logger, typeFinder); mock.Setup(x => x.GetInstance(typeof (ILogger))).Returns(logger); diff --git a/src/Umbraco.Tests/IO/PhysicalFileSystemTests.cs b/src/Umbraco.Tests/IO/PhysicalFileSystemTests.cs index ab9b2cf73d..85c10b4005 100644 --- a/src/Umbraco.Tests/IO/PhysicalFileSystemTests.cs +++ b/src/Umbraco.Tests/IO/PhysicalFileSystemTests.cs @@ -14,7 +14,7 @@ namespace Umbraco.Tests.IO { public PhysicalFileSystemTests() : base(new PhysicalFileSystem(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FileSysTests"), - "/Media/")) + "/Media/", new IOHelper())) { } [SetUp] diff --git a/src/Umbraco.Tests/IO/ShadowFileSystemTests.cs b/src/Umbraco.Tests/IO/ShadowFileSystemTests.cs index 409fae6081..ef5bf33824 100644 --- a/src/Umbraco.Tests/IO/ShadowFileSystemTests.cs +++ b/src/Umbraco.Tests/IO/ShadowFileSystemTests.cs @@ -40,8 +40,9 @@ namespace Umbraco.Tests.IO private static void ClearFiles() { - TestHelper.DeleteDirectory(Current.IOHelper.MapPath("FileSysTests")); - TestHelper.DeleteDirectory(Current.IOHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs")); + var ioHelper = new IOHelper(); + TestHelper.DeleteDirectory(ioHelper.MapPath("FileSysTests")); + TestHelper.DeleteDirectory(ioHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs")); } private static string NormPath(string path) @@ -52,13 +53,15 @@ namespace Umbraco.Tests.IO [Test] public void ShadowDeleteDirectory() { - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); Directory.CreateDirectory(path + "/ShadowTests/d1"); @@ -86,13 +89,15 @@ namespace Umbraco.Tests.IO [Test] public void ShadowDeleteDirectoryInDir() { - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); Directory.CreateDirectory(path + "/ShadowTests/sub"); @@ -135,13 +140,15 @@ namespace Umbraco.Tests.IO [Test] public void ShadowDeleteFile() { - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); File.WriteAllText(path + "/ShadowTests/f1.txt", "foo"); @@ -174,13 +181,16 @@ namespace Umbraco.Tests.IO [Test] public void ShadowDeleteFileInDir() { - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); + Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); Directory.CreateDirectory(path + "/ShadowTests/sub"); @@ -229,13 +239,15 @@ namespace Umbraco.Tests.IO [Test] public void ShadowCantCreateFile() { - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); Assert.Throws(() => @@ -248,13 +260,15 @@ namespace Umbraco.Tests.IO [Test] public void ShadowCreateFile() { - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); File.WriteAllText(path + "/ShadowTests/f2.txt", "foo"); @@ -287,13 +301,15 @@ namespace Umbraco.Tests.IO [Test] public void ShadowCreateFileInDir() { - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) @@ -327,13 +343,15 @@ namespace Umbraco.Tests.IO [Test] public void ShadowAbort() { - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) @@ -349,13 +367,15 @@ namespace Umbraco.Tests.IO [Test] public void ShadowComplete() { - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); Directory.CreateDirectory(path + "/ShadowTests/sub/sub"); @@ -386,18 +406,19 @@ namespace Umbraco.Tests.IO public void ShadowScopeComplete() { var logger = Mock.Of(); + var ioHelper = new IOHelper(); - var path = Current.IOHelper.MapPath("FileSysTests"); - var shadowfs = Current.IOHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs"); + var path = ioHelper.MapPath("FileSysTests"); + var shadowfs = ioHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs"); Directory.CreateDirectory(path); Directory.CreateDirectory(shadowfs); var scopedFileSystems = false; - var phy = new PhysicalFileSystem(path, "ignore"); + var phy = new PhysicalFileSystem(path, "ignore", ioHelper); var container = Mock.Of(); - var fileSystems = new FileSystems(container, logger) { IsScoped = () => scopedFileSystems }; + var fileSystems = new FileSystems(container, logger, ioHelper) { IsScoped = () => scopedFileSystems }; var fs = fileSystems.GetFileSystem(phy); var sw = (ShadowWrapper) fs.InnerFileSystem; @@ -481,17 +502,18 @@ namespace Umbraco.Tests.IO public void ShadowScopeCompleteWithFileConflict() { var logger = Mock.Of(); + var ioHelper = new IOHelper(); - var path = Current.IOHelper.MapPath("FileSysTests"); - var shadowfs = Current.IOHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs"); + var path = ioHelper.MapPath("FileSysTests"); + var shadowfs = ioHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs"); Directory.CreateDirectory(path); var scopedFileSystems = false; - var phy = new PhysicalFileSystem(path, "ignore"); + var phy = new PhysicalFileSystem(path, "ignore", ioHelper); var container = Mock.Of(); - var fileSystems = new FileSystems(container, logger) { IsScoped = () => scopedFileSystems }; + var fileSystems = new FileSystems(container, logger, ioHelper) { IsScoped = () => scopedFileSystems }; var fs = fileSystems.GetFileSystem( phy); var sw = (ShadowWrapper) fs.InnerFileSystem; @@ -534,17 +556,18 @@ namespace Umbraco.Tests.IO public void ShadowScopeCompleteWithDirectoryConflict() { var logger = Mock.Of(); + var ioHelper = new IOHelper(); - var path = Current.IOHelper.MapPath("FileSysTests"); - var shadowfs = Current.IOHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs"); + var path = ioHelper.MapPath("FileSysTests"); + var shadowfs = ioHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs"); Directory.CreateDirectory(path); var scopedFileSystems = false; - var phy = new PhysicalFileSystem(path, "ignore"); + var phy = new PhysicalFileSystem(path, "ignore", ioHelper); var container = Mock.Of(); - var fileSystems = new FileSystems(container, logger) { IsScoped = () => scopedFileSystems }; + var fileSystems = new FileSystems(container, logger, ioHelper) { IsScoped = () => scopedFileSystems }; var fs = fileSystems.GetFileSystem( phy); var sw = (ShadowWrapper)fs.InnerFileSystem; @@ -603,7 +626,9 @@ namespace Umbraco.Tests.IO [Test] public void GetFilesReturnsChildrenOnly() { - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); File.WriteAllText(path + "/f1.txt", "foo"); Directory.CreateDirectory(path + "/test"); @@ -625,7 +650,9 @@ namespace Umbraco.Tests.IO [Test] public void DeleteDirectoryAndFiles() { - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); File.WriteAllText(path + "/f1.txt", "foo"); Directory.CreateDirectory(path + "/test"); @@ -646,13 +673,15 @@ namespace Umbraco.Tests.IO public void ShadowGetFiles() { // Arrange - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); // Act @@ -678,13 +707,15 @@ namespace Umbraco.Tests.IO public void ShadowGetFilesUsingEmptyFilter() { // Arrange - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); // Act @@ -713,13 +744,15 @@ namespace Umbraco.Tests.IO public void ShadowGetFilesUsingNullFilter() { // Arrange - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); // Act @@ -745,13 +778,15 @@ namespace Umbraco.Tests.IO public void ShadowGetFilesUsingWildcardFilter() { // Arrange - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); // Act @@ -780,13 +815,15 @@ namespace Umbraco.Tests.IO public void ShadowGetFilesUsingSingleCharacterFilter() { // Arrange - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); // Act @@ -827,13 +864,15 @@ namespace Umbraco.Tests.IO public void ShadowGetFullPath() { // Arrange - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); // Act @@ -861,13 +900,15 @@ namespace Umbraco.Tests.IO public void ShadowGetRelativePath() { // Arrange - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "ignore", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "ignore", ioHelper); var ss = new ShadowFileSystem(fs, sfs); // Act @@ -900,13 +941,15 @@ namespace Umbraco.Tests.IO public void ShadowGetUrl() { // Arrange - var path = Current.IOHelper.MapPath("FileSysTests"); + var ioHelper = new IOHelper(); + + var path = ioHelper.MapPath("FileSysTests"); Directory.CreateDirectory(path); Directory.CreateDirectory(path + "/ShadowTests"); Directory.CreateDirectory(path + "/ShadowSystem"); - var fs = new PhysicalFileSystem(path + "/ShadowTests/", "rootUrl"); - var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "rootUrl"); + var fs = new PhysicalFileSystem(path + "/ShadowTests/", "rootUrl", ioHelper); + var sfs = new PhysicalFileSystem(path + "/ShadowSystem/", "rootUrl", ioHelper); var ss = new ShadowFileSystem(fs, sfs); // Act diff --git a/src/Umbraco.Tests/Logging/LogviewerTests.cs b/src/Umbraco.Tests/Logging/LogviewerTests.cs index 96a68beccb..d6e1c7ffae 100644 --- a/src/Umbraco.Tests/Logging/LogviewerTests.cs +++ b/src/Umbraco.Tests/Logging/LogviewerTests.cs @@ -33,6 +33,7 @@ namespace Umbraco.Tests.Logging { //Create an example JSON log file to check results //As a one time setup for all tets in this class/fixture + var ioHelper = new IOHelper(); var exampleLogfilePath = Path.Combine(TestContext.CurrentContext.TestDirectory, @"Logging\", _logfileName); _newLogfileDirPath = Path.Combine(TestContext.CurrentContext.TestDirectory, @"App_Data\Logs\"); @@ -43,15 +44,15 @@ namespace Umbraco.Tests.Logging _newSearchfilePath = Path.Combine(_newSearchfileDirPath, _searchfileName); //Create/ensure Directory exists - Current.IOHelper.EnsurePathExists(_newLogfileDirPath); - Current.IOHelper.EnsurePathExists(_newSearchfileDirPath); + ioHelper.EnsurePathExists(_newLogfileDirPath); + ioHelper.EnsurePathExists(_newSearchfileDirPath); //Copy the sample files File.Copy(exampleLogfilePath, _newLogfilePath, true); File.Copy(exampleSearchfilePath, _newSearchfilePath, true); var logger = Mock.Of(); - _logViewer = new JsonLogViewer(logger, logsPath: _newLogfileDirPath, searchPath: _newSearchfilePath); + _logViewer = new JsonLogViewer(logger, ioHelper, logsPath: _newLogfileDirPath, searchPath: _newSearchfilePath); } [OneTimeTearDown] diff --git a/src/Umbraco.Tests/Manifest/ManifestParserTests.cs b/src/Umbraco.Tests/Manifest/ManifestParserTests.cs index 1c90f68d62..dff37edc74 100644 --- a/src/Umbraco.Tests/Manifest/ManifestParserTests.cs +++ b/src/Umbraco.Tests/Manifest/ManifestParserTests.cs @@ -13,6 +13,7 @@ using Umbraco.Core.PropertyEditors; using Umbraco.Core.PropertyEditors.Validators; using Umbraco.Core.Services; using Umbraco.Core.Dashboards; +using Umbraco.Core.IO; namespace Umbraco.Tests.Manifest { @@ -44,7 +45,7 @@ namespace Umbraco.Tests.Manifest new RequiredValidator(Mock.Of()), new RegexValidator(Mock.Of(), null) }; - _parser = new ManifestParser(AppCaches.Disabled, new ManifestValueValidatorCollection(validators), new ManifestFilterCollection(Array.Empty()), Mock.Of()); + _parser = new ManifestParser(AppCaches.Disabled, new ManifestValueValidatorCollection(validators), new ManifestFilterCollection(Array.Empty()), Mock.Of(), Mock.Of()); } [Test] diff --git a/src/Umbraco.Tests/Models/MediaXmlTest.cs b/src/Umbraco.Tests/Models/MediaXmlTest.cs index 3ae9414dc1..d7daf35865 100644 --- a/src/Umbraco.Tests/Models/MediaXmlTest.cs +++ b/src/Umbraco.Tests/Models/MediaXmlTest.cs @@ -33,8 +33,9 @@ namespace Umbraco.Tests.Models var logger = Mock.Of(); var scheme = Mock.Of(); var config = Mock.Of(); + var ioHelper = Mock.Of(); - var mediaFileSystem = new MediaFileSystem(Mock.Of(), config, scheme, logger); + var mediaFileSystem = new MediaFileSystem(Mock.Of(), config, scheme, logger, ioHelper); var ignored = new FileUploadPropertyEditor(Mock.Of(), mediaFileSystem, config); var media = MockedMedia.CreateMediaImage(mediaType, -1); diff --git a/src/Umbraco.Tests/Packaging/PackageInstallationTest.cs b/src/Umbraco.Tests/Packaging/PackageInstallationTest.cs index 14a7049195..8b33859e5b 100644 --- a/src/Umbraco.Tests/Packaging/PackageInstallationTest.cs +++ b/src/Umbraco.Tests/Packaging/PackageInstallationTest.cs @@ -35,7 +35,7 @@ namespace Umbraco.Tests.Packaging base.TearDown(); //clear out files/folders - var path = Current.IOHelper.MapPath("~/" + _testBaseFolder); + var path = IOHelper.MapPath("~/" + _testBaseFolder); if (Directory.Exists(path)) Directory.Delete(path, true); } @@ -51,9 +51,9 @@ namespace Umbraco.Tests.Packaging private IPackageInstallation PackageInstallation => new PackageInstallation( PackageDataInstallation, - new PackageFileInstallation(Parser, ProfilingLogger), + new PackageFileInstallation(Parser, IOHelper, ProfilingLogger), Parser, Mock.Of(), - applicationRootFolder: new DirectoryInfo(Current.IOHelper.MapPath("~/" + _testBaseFolder))); //we don't want to extract package files to the real root, so extract to a test folder + applicationRootFolder: new DirectoryInfo(IOHelper.MapPath("~/" + _testBaseFolder))); //we don't want to extract package files to the real root, so extract to a test folder private const string DocumentTypePickerPackage = "Document_Type_Picker_1.1.umb"; private const string HelloPackage = "Hello_1.0.0.zip"; @@ -63,7 +63,7 @@ namespace Umbraco.Tests.Packaging { var package = PackageInstallation.ReadPackage( //this is where our test zip file is - new FileInfo(Path.Combine(Current.IOHelper.MapPath("~/Packaging/packages"), DocumentTypePickerPackage))); + new FileInfo(Path.Combine(IOHelper.MapPath("~/Packaging/packages"), DocumentTypePickerPackage))); Assert.IsNotNull(package); Assert.AreEqual(1, package.Files.Count); Assert.AreEqual("095e064b-ba4d-442d-9006-3050983c13d8.dll", package.Files[0].UniqueFileName); @@ -86,7 +86,7 @@ namespace Umbraco.Tests.Packaging { var package = PackageInstallation.ReadPackage( //this is where our test zip file is - new FileInfo(Path.Combine(Current.IOHelper.MapPath("~/Packaging/packages"), HelloPackage))); + new FileInfo(Path.Combine(IOHelper.MapPath("~/Packaging/packages"), HelloPackage))); Assert.IsNotNull(package); Assert.AreEqual(0, package.Files.Count); Assert.AreEqual("Hello", package.Name); @@ -111,7 +111,7 @@ namespace Umbraco.Tests.Packaging public void Can_Read_Compiled_Package_Warnings() { //copy a file to the same path that the package will install so we can detect file conflicts - var path = Current.IOHelper.MapPath("~/" + _testBaseFolder); + var path = IOHelper.MapPath("~/" + _testBaseFolder); Console.WriteLine(path); var filePath = Path.Combine(path, "bin", "Auros.DocumentTypePicker.dll"); @@ -119,7 +119,7 @@ namespace Umbraco.Tests.Packaging File.WriteAllText(filePath, "test"); //this is where our test zip file is - var packageFile = Path.Combine(Current.IOHelper.MapPath("~/Packaging/packages"), DocumentTypePickerPackage); + var packageFile = Path.Combine(IOHelper.MapPath("~/Packaging/packages"), DocumentTypePickerPackage); Console.WriteLine(packageFile); var package = PackageInstallation.ReadPackage(new FileInfo(packageFile)); @@ -137,7 +137,7 @@ namespace Umbraco.Tests.Packaging { var package = PackageInstallation.ReadPackage( //this is where our test zip file is - new FileInfo(Path.Combine(Current.IOHelper.MapPath("~/Packaging/packages"), DocumentTypePickerPackage))); + new FileInfo(Path.Combine(IOHelper.MapPath("~/Packaging/packages"), DocumentTypePickerPackage))); var def = PackageDefinition.FromCompiledPackage(package); def.Id = 1; @@ -148,7 +148,7 @@ namespace Umbraco.Tests.Packaging Assert.AreEqual(1, result.Count); Assert.AreEqual("bin\\Auros.DocumentTypePicker.dll", result[0]); - Assert.IsTrue(File.Exists(Path.Combine(Current.IOHelper.MapPath("~/" + _testBaseFolder), result[0]))); + Assert.IsTrue(File.Exists(Path.Combine(IOHelper.MapPath("~/" + _testBaseFolder), result[0]))); //make sure the def is updated too Assert.AreEqual(result.Count, def.Files.Count); @@ -159,7 +159,7 @@ namespace Umbraco.Tests.Packaging { var package = PackageInstallation.ReadPackage( //this is where our test zip file is - new FileInfo(Path.Combine(Current.IOHelper.MapPath("~/Packaging/packages"), DocumentTypePickerPackage))); + new FileInfo(Path.Combine(IOHelper.MapPath("~/Packaging/packages"), DocumentTypePickerPackage))); var def = PackageDefinition.FromCompiledPackage(package); def.Id = 1; def.PackageId = Guid.NewGuid(); diff --git a/src/Umbraco.Tests/Persistence/Repositories/PartialViewRepositoryTests.cs b/src/Umbraco.Tests/Persistence/Repositories/PartialViewRepositoryTests.cs index 9c326b3ddc..970e078d41 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/PartialViewRepositoryTests.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/PartialViewRepositoryTests.cs @@ -20,7 +20,7 @@ namespace Umbraco.Tests.Persistence.Repositories { base.SetUp(); - _fileSystem = new PhysicalFileSystem(SystemDirectories.MvcViews + "/Partials/"); + _fileSystem = new PhysicalFileSystem(SystemDirectories.MvcViews + "/Partials/", new IOHelper()); } protected override void Compose() @@ -41,7 +41,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new PartialViewRepository(fileSystems); + var repository = new PartialViewRepository(fileSystems, IOHelper); var partialView = new PartialView(PartialViewType.PartialView, "test-path-1.cshtml") { Content = "// partialView" }; repository.Save(partialView); diff --git a/src/Umbraco.Tests/Persistence/Repositories/ScriptRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/ScriptRepositoryTest.cs index ae0c71a5b3..d1aa20db66 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/ScriptRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/ScriptRepositoryTest.cs @@ -26,7 +26,7 @@ namespace Umbraco.Tests.Persistence.Repositories base.SetUp(); _fileSystems = Mock.Of(); - _fileSystem = new PhysicalFileSystem(SystemDirectories.Scripts); + _fileSystem = new PhysicalFileSystem(SystemDirectories.Scripts, new IOHelper()); Mock.Get(_fileSystems).Setup(x => x.ScriptsFileSystem).Returns(_fileSystem); using (var stream = CreateStream("Umbraco.Sys.registerNamespace(\"Umbraco.Utils\");")) { diff --git a/src/Umbraco.Tests/Persistence/Repositories/StylesheetRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/StylesheetRepositoryTest.cs index 2358fb257d..5443ca52ec 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/StylesheetRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/StylesheetRepositoryTest.cs @@ -25,7 +25,7 @@ namespace Umbraco.Tests.Persistence.Repositories base.SetUp(); _fileSystems = Mock.Of(); - _fileSystem = new PhysicalFileSystem(SystemDirectories.Css); + _fileSystem = new PhysicalFileSystem(SystemDirectories.Css, new IOHelper()); Mock.Get(_fileSystems).Setup(x => x.StylesheetsFileSystem).Returns(_fileSystem); var stream = CreateStream("body {background:#EE7600; color:#FFF;}"); _fileSystem.AddFile("styles.css", stream); diff --git a/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs index b0f9a5335b..2d6c42ef06 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs @@ -27,7 +27,7 @@ namespace Umbraco.Tests.Persistence.Repositories private ITemplateRepository CreateRepository(IScopeProvider provider) { - return new TemplateRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, _fileSystems); + return new TemplateRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, _fileSystems, IOHelper); } public override void SetUp() @@ -35,7 +35,7 @@ namespace Umbraco.Tests.Persistence.Repositories base.SetUp(); _fileSystems = Mock.Of(); - var viewsFileSystem = new PhysicalFileSystem(SystemDirectories.MvcViews); + var viewsFileSystem = new PhysicalFileSystem(SystemDirectories.MvcViews, IOHelper); Mock.Get(_fileSystems).Setup(x => x.MvcViewsFileSystem).Returns(viewsFileSystem); } @@ -526,7 +526,7 @@ namespace Umbraco.Tests.Persistence.Repositories _fileSystems = null; //Delete all files - var fsViews = new PhysicalFileSystem(SystemDirectories.MvcViews); + var fsViews = new PhysicalFileSystem(SystemDirectories.MvcViews, new IOHelper()); var views = fsViews.GetFiles("", "*.cshtml"); foreach (var file in views) fsViews.DeleteFile(file); diff --git a/src/Umbraco.Tests/PropertyEditors/ImageCropperTest.cs b/src/Umbraco.Tests/PropertyEditors/ImageCropperTest.cs index 5bea491973..01486d70c8 100644 --- a/src/Umbraco.Tests/PropertyEditors/ImageCropperTest.cs +++ b/src/Umbraco.Tests/PropertyEditors/ImageCropperTest.cs @@ -79,8 +79,9 @@ namespace Umbraco.Tests.PropertyEditors var logger = Mock.Of(); var scheme = Mock.Of(); var config = Mock.Of(); + var ioHelper = Mock.Of(); - var mediaFileSystem = new MediaFileSystem(Mock.Of(), config, scheme, logger); + var mediaFileSystem = new MediaFileSystem(Mock.Of(), config, scheme, logger, ioHelper); var dataTypeService = new TestObjects.TestDataTypeService( new DataType(new ImageCropperPropertyEditor(Mock.Of(), mediaFileSystem, Mock.Of(), Mock.Of())) { Id = 1 }); diff --git a/src/Umbraco.Tests/Scoping/ScopeEventDispatcherTests.cs b/src/Umbraco.Tests/Scoping/ScopeEventDispatcherTests.cs index 74e79c4ce3..2ede62f81e 100644 --- a/src/Umbraco.Tests/Scoping/ScopeEventDispatcherTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopeEventDispatcherTests.cs @@ -36,7 +36,7 @@ namespace Umbraco.Tests.Scoping _testObjects = new TestObjects(register); - composition.RegisterUnique(factory => new FileSystems(factory, factory.TryGetInstance())); + composition.RegisterUnique(factory => new FileSystems(factory, factory.TryGetInstance(), factory.TryGetInstance())); composition.WithCollectionBuilder(); composition.Configs.Add(SettingsForTests.GetDefaultGlobalSettings); diff --git a/src/Umbraco.Tests/Scoping/ScopeFileSystemsTests.cs b/src/Umbraco.Tests/Scoping/ScopeFileSystemsTests.cs index 305ae70be9..7abf8eece3 100644 --- a/src/Umbraco.Tests/Scoping/ScopeFileSystemsTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopeFileSystemsTests.cs @@ -21,7 +21,7 @@ namespace Umbraco.Tests.Scoping base.SetUp(); SafeCallContext.Clear(); - ClearFiles(); + ClearFiles(this.IOHelper); } protected override void ComposeApplication(bool withApplication) @@ -39,21 +39,21 @@ namespace Umbraco.Tests.Scoping base.TearDown(); SafeCallContext.Clear(); FileSystems.ResetShadowId(); - ClearFiles(); + ClearFiles(this.IOHelper); } - private static void ClearFiles() + private static void ClearFiles(IIOHelper ioHelper) { - TestHelper.DeleteDirectory(Current.IOHelper.MapPath("media")); - TestHelper.DeleteDirectory(Current.IOHelper.MapPath("FileSysTests")); - TestHelper.DeleteDirectory(Current.IOHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs")); + TestHelper.DeleteDirectory(ioHelper.MapPath("media")); + TestHelper.DeleteDirectory(ioHelper.MapPath("FileSysTests")); + TestHelper.DeleteDirectory(ioHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs")); } [TestCase(true)] [TestCase(false)] public void CreateMediaTest(bool complete) { - var physMediaFileSystem = new PhysicalFileSystem(Current.IOHelper.MapPath("media"), "ignore"); + var physMediaFileSystem = new PhysicalFileSystem(IOHelper.MapPath("media"), "ignore", IOHelper); var mediaFileSystem = Current.MediaFileSystem; Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); @@ -86,7 +86,7 @@ namespace Umbraco.Tests.Scoping [Test] public void MultiThread() { - var physMediaFileSystem = new PhysicalFileSystem(Current.IOHelper.MapPath("media"), "ignore"); + var physMediaFileSystem = new PhysicalFileSystem(IOHelper.MapPath("media"), "ignore", new IOHelper()); var mediaFileSystem = Current.MediaFileSystem; var scopeProvider = ScopeProvider; diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects.cs b/src/Umbraco.Tests/TestHelpers/TestObjects.cs index 280632fdae..eaade28c2e 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects.cs @@ -107,8 +107,9 @@ namespace Umbraco.Tests.TestHelpers var scheme = Mock.Of(); var config = Mock.Of(); + var ioHelper = Mock.Of(); - var mediaFileSystem = new MediaFileSystem(Mock.Of(), config, scheme, logger); + var mediaFileSystem = new MediaFileSystem(Mock.Of(), config, scheme, logger, ioHelper); var externalLoginService = GetLazyService(factory, c => new ExternalLoginService(scopeProvider, logger, eventMessagesFactory, GetRepo(c))); var publicAccessService = GetLazyService(factory, c => new PublicAccessService(scopeProvider, logger, eventMessagesFactory, GetRepo(c))); @@ -118,9 +119,9 @@ namespace Umbraco.Tests.TestHelpers var localizedTextService = GetLazyService(factory, c => new LocalizedTextService( new Lazy(() => { - var mainLangFolder = new DirectoryInfo(Current.IOHelper.MapPath(SystemDirectories.Umbraco + "/config/lang/")); - var appPlugins = new DirectoryInfo(Current.IOHelper.MapPath(SystemDirectories.AppPlugins)); - var configLangFolder = new DirectoryInfo(Current.IOHelper.MapPath(SystemDirectories.Config + "/lang/")); + var mainLangFolder = new DirectoryInfo(ioHelper.MapPath(SystemDirectories.Umbraco + "/config/lang/")); + var appPlugins = new DirectoryInfo(ioHelper.MapPath(SystemDirectories.AppPlugins)); + var configLangFolder = new DirectoryInfo(ioHelper.MapPath(SystemDirectories.Config + "/lang/")); var pluginLangFolders = appPlugins.Exists == false ? Enumerable.Empty() @@ -154,14 +155,14 @@ namespace Umbraco.Tests.TestHelpers var userService = GetLazyService(factory, c => new UserService(scopeProvider, logger, eventMessagesFactory, runtimeState, GetRepo(c), GetRepo(c),globalSettings)); var dataTypeService = GetLazyService(factory, c => new DataTypeService(scopeProvider, logger, eventMessagesFactory, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); var contentService = GetLazyService(factory, c => new ContentService(scopeProvider, logger, eventMessagesFactory, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); - var notificationService = GetLazyService(factory, c => new NotificationService(scopeProvider, userService.Value, contentService.Value, localizationService.Value, logger, GetRepo(c), globalSettings, umbracoSettings.Content)); + var notificationService = GetLazyService(factory, c => new NotificationService(scopeProvider, userService.Value, contentService.Value, localizationService.Value, logger, ioHelper, GetRepo(c), globalSettings, umbracoSettings.Content)); var serverRegistrationService = GetLazyService(factory, c => new ServerRegistrationService(scopeProvider, logger, eventMessagesFactory, GetRepo(c))); var memberGroupService = GetLazyService(factory, c => new MemberGroupService(scopeProvider, logger, eventMessagesFactory, GetRepo(c))); var memberService = GetLazyService(factory, c => new MemberService(scopeProvider, logger, eventMessagesFactory, memberGroupService.Value, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); var mediaService = GetLazyService(factory, c => new MediaService(scopeProvider, mediaFileSystem, logger, eventMessagesFactory, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); var contentTypeService = GetLazyService(factory, c => new ContentTypeService(scopeProvider, logger, eventMessagesFactory, contentService.Value, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); var mediaTypeService = GetLazyService(factory, c => new MediaTypeService(scopeProvider, logger, eventMessagesFactory, mediaService.Value, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); - var fileService = GetLazyService(factory, c => new FileService(scopeProvider, logger, eventMessagesFactory, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); + var fileService = GetLazyService(factory, c => new FileService(scopeProvider, ioHelper, logger, eventMessagesFactory, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); var memberTypeService = GetLazyService(factory, c => new MemberTypeService(scopeProvider, logger, eventMessagesFactory, memberService.Value, GetRepo(c), GetRepo(c), GetRepo(c))); var entityService = GetLazyService(factory, c => new EntityService(scopeProvider, logger, eventMessagesFactory, idkMap, GetRepo(c))); @@ -173,15 +174,15 @@ namespace Umbraco.Tests.TestHelpers var compiledPackageXmlParser = new CompiledPackageXmlParser(new ConflictingPackageData(macroService.Value, fileService.Value)); return new PackagingService( auditService.Value, - new PackagesRepository(contentService.Value, contentTypeService.Value, dataTypeService.Value, fileService.Value, macroService.Value, localizationService.Value, + new PackagesRepository(contentService.Value, contentTypeService.Value, dataTypeService.Value, fileService.Value, macroService.Value, localizationService.Value, ioHelper, new EntityXmlSerializer(contentService.Value, mediaService.Value, dataTypeService.Value, userService.Value, localizationService.Value, contentTypeService.Value, urlSegmentProviders), logger, "createdPackages.config"), - new PackagesRepository(contentService.Value, contentTypeService.Value, dataTypeService.Value, fileService.Value, macroService.Value, localizationService.Value, + new PackagesRepository(contentService.Value, contentTypeService.Value, dataTypeService.Value, fileService.Value, macroService.Value, localizationService.Value, ioHelper, new EntityXmlSerializer(contentService.Value, mediaService.Value, dataTypeService.Value, userService.Value, localizationService.Value, contentTypeService.Value, urlSegmentProviders), logger, "installedPackages.config"), new PackageInstallation( new PackageDataInstallation(logger, fileService.Value, macroService.Value, localizationService.Value, dataTypeService.Value, entityService.Value, contentTypeService.Value, contentService.Value, propertyEditorCollection, scopeProvider), - new PackageFileInstallation(compiledPackageXmlParser, new ProfilingLogger(logger, new TestProfiler())), + new PackageFileInstallation(compiledPackageXmlParser, ioHelper, new ProfilingLogger(logger, new TestProfiler())), compiledPackageXmlParser, Mock.Of(), - new DirectoryInfo(Current.IOHelper.GetRootDirectorySafe()))); + new DirectoryInfo(ioHelper.GetRootDirectorySafe())), ioHelper); }); var relationService = GetLazyService(factory, c => new RelationService(scopeProvider, logger, eventMessagesFactory, entityService.Value, GetRepo(c), GetRepo(c))); var tagService = GetLazyService(factory, c => new TagService(scopeProvider, logger, eventMessagesFactory, GetRepo(c))); @@ -242,7 +243,7 @@ namespace Umbraco.Tests.TestHelpers } typeFinder = typeFinder ?? new TypeFinder(logger); - fileSystems = fileSystems ?? new FileSystems(Current.Factory, logger); + fileSystems = fileSystems ?? new FileSystems(Current.Factory, logger, new IOHelper()); var scopeProvider = new ScopeProvider(databaseFactory, fileSystems, logger, typeFinder); return scopeProvider; } diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index d1e2ab2f6d..1dec01a4e9 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -342,8 +342,9 @@ namespace Umbraco.Tests.Testing var logger = Mock.Of(); var scheme = Mock.Of(); var config = Mock.Of(); + var ioHelper = Mock.Of(); - var mediaFileSystem = new MediaFileSystem(Mock.Of(), config, scheme, logger); + var mediaFileSystem = new MediaFileSystem(Mock.Of(), config, scheme, logger, ioHelper); Composition.RegisterUnique(factory => mediaFileSystem); // no factory (noop) diff --git a/src/Umbraco.Web/Editors/BackOfficeAssetsController.cs b/src/Umbraco.Web/Editors/BackOfficeAssetsController.cs index 6b1b12ab63..e1302d7e5a 100644 --- a/src/Umbraco.Web/Editors/BackOfficeAssetsController.cs +++ b/src/Umbraco.Web/Editors/BackOfficeAssetsController.cs @@ -11,7 +11,14 @@ namespace Umbraco.Web.Editors [PluginController("UmbracoApi")] public class BackOfficeAssetsController : UmbracoAuthorizedJsonController { - private readonly IFileSystem _jsLibFileSystem = new PhysicalFileSystem(SystemDirectories.Umbraco + Current.IOHelper.DirSepChar + "lib"); + private readonly IIOHelper _ioHelper; + private readonly IFileSystem _jsLibFileSystem; + + public BackOfficeAssetsController(IFileSystem jsLibFileSystem, IIOHelper ioHelper) + { + _ioHelper = ioHelper; + _jsLibFileSystem = new PhysicalFileSystem(SystemDirectories.Umbraco + _ioHelper.DirSepChar + "lib", _ioHelper); + } [HttpGet] public object GetSupportedLocales() diff --git a/src/Umbraco.Web/Trees/FilesTreeController.cs b/src/Umbraco.Web/Trees/FilesTreeController.cs index ae951bebf4..0a15ae32ea 100644 --- a/src/Umbraco.Web/Trees/FilesTreeController.cs +++ b/src/Umbraco.Web/Trees/FilesTreeController.cs @@ -8,10 +8,19 @@ namespace Umbraco.Web.Trees [CoreTree] public class FilesTreeController : FileSystemTreeController { - protected override IFileSystem FileSystem => new PhysicalFileSystem("~/"); + private readonly IIOHelper _ioHelper; + private readonly IFileSystem _fileSystem; + + protected override IFileSystem FileSystem => _fileSystem; private static readonly string[] ExtensionsStatic = { "*" }; + public FilesTreeController(IIOHelper ioHelper) + { + _ioHelper = ioHelper; + _fileSystem = new PhysicalFileSystem("~/", _ioHelper); + } + protected override string[] Extensions => ExtensionsStatic; protected override string FileIcon => Constants.Icons.MediaFile; diff --git a/src/Umbraco.Web/WebApi/HttpActionContextExtensions.cs b/src/Umbraco.Web/WebApi/HttpActionContextExtensions.cs index 8896e3ff7a..979e3d7892 100644 --- a/src/Umbraco.Web/WebApi/HttpActionContextExtensions.cs +++ b/src/Umbraco.Web/WebApi/HttpActionContextExtensions.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Controllers; using Newtonsoft.Json; +using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.IO; @@ -59,7 +60,8 @@ namespace Umbraco.Web.WebApi throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } - var root = Current.IOHelper.MapPath(rootVirtualPath); + var ioHelper = Current.Factory.GetInstance(); + var root = ioHelper.MapPath(rootVirtualPath); //ensure it exists Directory.CreateDirectory(root); var provider = new MultipartFormDataStreamProvider(root);