diff --git a/src/Libraries/Nop.Core/CommonHelper.cs b/src/Libraries/Nop.Core/CommonHelper.cs
index 7887d615eee..53eaac5bcf8 100644
--- a/src/Libraries/Nop.Core/CommonHelper.cs
+++ b/src/Libraries/Nop.Core/CommonHelper.cs
@@ -2,13 +2,12 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
-using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
-using System.Threading;
+using Nop.Core.Infrastructure;
namespace Nop.Core
{
@@ -34,29 +33,6 @@ static CommonHelper()
#endregion
- #region Utilities
-
- private static void DeleteDirectoryRecursive(string path)
- {
- Directory.Delete(path, true);
- const int maxIterationToWait = 10;
- var curIteration = 0;
-
- //according to the documentation(https://msdn.microsoft.com/ru-ru/library/windows/desktop/aa365488.aspx)
- //System.IO.Directory.Delete method ultimately (after removing the files) calls native
- //RemoveDirectory function which marks the directory as "deleted". That's why we wait until
- //the directory is actually deleted. For more details see https://stackoverflow.com/a/4245121
- while (Directory.Exists(path))
- {
- curIteration += 1;
- if (curIteration > maxIterationToWait)
- return;
- Thread.Sleep(100);
- }
- }
-
- #endregion
-
#region Methods
///
@@ -338,17 +314,6 @@ public static int GetDifferenceInYears(DateTime startDate, DateTime endDate)
return age;
}
- ///
- /// Maps a virtual path to a physical disk path.
- ///
- /// The path to map. E.g. "~/bin"
- /// The physical path. E.g. "c:\inetpub\wwwroot\bin"
- public static string MapPath(string path)
- {
- path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\');
- return Path.Combine(BaseDirectory??string.Empty, path);
- }
-
///
/// Get private fields property value
///
@@ -387,46 +352,15 @@ public static object GetPrivateFieldValue(object target, string fieldName)
return fi.GetValue(target);
}
- ///
- /// Depth-first recursive delete, with handling for descendant directories open in Windows Explorer.
- ///
- /// Directory path
- public static void DeleteDirectory(string path)
- {
- if (string.IsNullOrEmpty(path))
- throw new ArgumentNullException(path);
-
- //find more info about directory deletion
- //and why we use this approach at https://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true
-
- foreach (var directory in Directory.GetDirectories(path))
- {
- DeleteDirectory(directory);
- }
-
- try
- {
- DeleteDirectoryRecursive(path);
- }
- catch (IOException)
- {
- DeleteDirectoryRecursive(path);
- }
- catch (UnauthorizedAccessException)
- {
- DeleteDirectoryRecursive(path);
- }
- }
-
#endregion
#region Properties
///
- /// Gets or sets application base path
+ /// Gets or sets the default file provider
///
- internal static string BaseDirectory { get; set; }
-
+ public static INopFileProvider DefaultFileProvider { get; set; }
+
#endregion
}
}
diff --git a/src/Libraries/Nop.Core/Data/DataSettingsHelper.cs b/src/Libraries/Nop.Core/Data/DataSettingsHelper.cs
index 25788ae2ca6..56eb3ee2635 100644
--- a/src/Libraries/Nop.Core/Data/DataSettingsHelper.cs
+++ b/src/Libraries/Nop.Core/Data/DataSettingsHelper.cs
@@ -13,12 +13,13 @@ public partial class DataSettingsHelper
///
public static bool DatabaseIsInstalled()
{
- if (!_databaseIsInstalled.HasValue)
- {
- var manager = new DataSettingsManager();
- var settings = manager.LoadSettings(reloadSettings:true);
- _databaseIsInstalled = settings != null && !string.IsNullOrEmpty(settings.DataConnectionString);
- }
+ if (_databaseIsInstalled.HasValue)
+ return _databaseIsInstalled.Value;
+
+ var manager = new DataSettingsManager();
+
+ var settings = manager.LoadSettings(reloadSettings:true);
+ _databaseIsInstalled = !string.IsNullOrEmpty(settings?.DataConnectionString);
return _databaseIsInstalled.Value;
}
diff --git a/src/Libraries/Nop.Core/Data/DataSettingsManager.cs b/src/Libraries/Nop.Core/Data/DataSettingsManager.cs
index c170fab0354..764c2a8d73a 100644
--- a/src/Libraries/Nop.Core/Data/DataSettingsManager.cs
+++ b/src/Libraries/Nop.Core/Data/DataSettingsManager.cs
@@ -1,5 +1,6 @@
using System;
using System.IO;
+using System.Text;
using Newtonsoft.Json;
using Nop.Core.Infrastructure;
@@ -12,8 +13,14 @@ public partial class DataSettingsManager
{
#region Const
- private const string ObsoleteDataSettingsFilePath = "~/App_Data/Settings.txt";
- private const string DataSettingsFilePath_ = "~/App_Data/dataSettings.json";
+ private const string OBSOLETE_DATA_SETTINGS_FILE_PATH = "~/App_Data/Settings.txt";
+ private const string DATA_SETTINGS_FILE_PATH_ = "~/App_Data/dataSettings.json";
+
+ #endregion
+
+ #region Fields
+
+ protected INopFileProvider _fileProvider;
#endregion
@@ -22,7 +29,16 @@ public partial class DataSettingsManager
///
/// Gets the path to file that contains data settings
///
- public static string DataSettingsFilePath => DataSettingsFilePath_;
+ public static string DataSettingsFilePath => DATA_SETTINGS_FILE_PATH_;
+
+ #endregion
+
+ #region Ctor
+
+ public DataSettingsManager(INopFileProvider fileProvider = null)
+ {
+ this._fileProvider = fileProvider ?? CommonHelper.DefaultFileProvider;
+ }
#endregion
@@ -39,21 +55,21 @@ public virtual DataSettings LoadSettings(string filePath = null, bool reloadSett
if (!reloadSettings && Singleton.Instance != null)
return Singleton.Instance;
- filePath = filePath ?? CommonHelper.MapPath(DataSettingsFilePath);
+ filePath = filePath ?? _fileProvider.MapPath(DataSettingsFilePath);
//check whether file exists
- if (!File.Exists(filePath))
+ if (!_fileProvider.FileExists(filePath))
{
//if not, try to parse the file that was used in previous nopCommerce versions
- filePath = CommonHelper.MapPath(ObsoleteDataSettingsFilePath);
- if (!File.Exists(filePath))
+ filePath = _fileProvider.MapPath(OBSOLETE_DATA_SETTINGS_FILE_PATH);
+ if (!_fileProvider.FileExists(filePath))
return new DataSettings();
//get data settings from the old txt file
var dataSettings = new DataSettings();
- using (var reader = new StringReader(File.ReadAllText(filePath)))
+ using (var reader = new StringReader(_fileProvider.ReadAllText(filePath, Encoding.UTF8)))
{
- var settingsLine = string.Empty;
+ string settingsLine;
while ((settingsLine = reader.ReadLine()) != null)
{
var separatorIndex = settingsLine.IndexOf(':');
@@ -82,13 +98,13 @@ public virtual DataSettings LoadSettings(string filePath = null, bool reloadSett
SaveSettings(dataSettings);
//and delete the old one
- File.Delete(filePath);
+ _fileProvider.DeleteFile(filePath);
Singleton.Instance = dataSettings;
return Singleton.Instance;
}
- var text = File.ReadAllText(filePath);
+ var text = _fileProvider.ReadAllText(filePath, Encoding.UTF8);
if (string.IsNullOrEmpty(text))
return new DataSettings();
@@ -104,19 +120,15 @@ public virtual DataSettings LoadSettings(string filePath = null, bool reloadSett
public virtual void SaveSettings(DataSettings settings)
{
Singleton.Instance = settings ?? throw new ArgumentNullException(nameof(settings));
-
- var filePath = CommonHelper.MapPath(DataSettingsFilePath);
+
+ var filePath = _fileProvider.MapPath(DataSettingsFilePath);
//create file if not exists
- if (!File.Exists(filePath))
- {
- //we use 'using' to close the file after it's created
- using (File.Create(filePath)) { }
- }
+ _fileProvider.CreateFile(filePath);
//save data settings to the file
var text = JsonConvert.SerializeObject(Singleton.Instance, Formatting.Indented);
- File.WriteAllText(filePath, text);
+ _fileProvider.WriteAllText(filePath, text, Encoding.UTF8);
}
#endregion
diff --git a/src/Libraries/Nop.Core/Infrastructure/AppDomainTypeFinder.cs b/src/Libraries/Nop.Core/Infrastructure/AppDomainTypeFinder.cs
index b314866ac4a..473ec0553c5 100644
--- a/src/Libraries/Nop.Core/Infrastructure/AppDomainTypeFinder.cs
+++ b/src/Libraries/Nop.Core/Infrastructure/AppDomainTypeFinder.cs
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
-using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
@@ -17,11 +16,17 @@ public class AppDomainTypeFinder : ITypeFinder
{
#region Fields
- private bool ignoreReflectionErrors = true;
- private bool loadAppDomainAssemblies = true;
- private string assemblySkipLoadingPattern = "^System|^mscorlib|^Microsoft|^AjaxControlToolkit|^Antlr3|^Autofac|^AutoMapper|^Castle|^ComponentArt|^CppCodeProvider|^DotNetOpenAuth|^EntityFramework|^EPPlus|^FluentValidation|^ImageResizer|^itextsharp|^log4net|^MaxMind|^MbUnit|^MiniProfiler|^Mono.Math|^MvcContrib|^Newtonsoft|^NHibernate|^nunit|^Org.Mentalis|^PerlRegex|^QuickGraph|^Recaptcha|^Remotion|^RestSharp|^Rhino|^Telerik|^Iesi|^TestDriven|^TestFu|^UserAgentStringLibrary|^VJSharpCodeProvider|^WebActivator|^WebDev|^WebGrease";
- private string assemblyRestrictToLoadingPattern = ".*";
- private IList assemblyNames = new List();
+ private bool _ignoreReflectionErrors = true;
+ protected INopFileProvider _fileProvider;
+
+ #endregion
+
+ #region Ctor
+
+ public AppDomainTypeFinder(INopFileProvider fileProvider = null)
+ {
+ this._fileProvider = fileProvider ?? CommonHelper.DefaultFileProvider;
+ }
#endregion
@@ -106,17 +111,18 @@ protected virtual bool Matches(string assemblyFullName, string pattern)
protected virtual void LoadMatchingAssemblies(string directoryPath)
{
var loadedAssemblyNames = new List();
+
foreach (var a in GetAssemblies())
{
loadedAssemblyNames.Add(a.FullName);
}
- if (!Directory.Exists(directoryPath))
+ if (!_fileProvider.DirectoryExists(directoryPath))
{
return;
}
- foreach (var dllPath in Directory.GetFiles(directoryPath, "*.dll"))
+ foreach (var dllPath in _fileProvider.GetFiles(directoryPath, "*.dll"))
{
try
{
@@ -228,7 +234,7 @@ public IEnumerable FindClassesOfType(Type assignTypeFrom, IEnumerableGets or sets whether Nop should iterate assemblies in the app domain when loading Nop types. Loading patterns are applied when loading these assemblies.
- public bool LoadAppDomainAssemblies
- {
- get { return loadAppDomainAssemblies; }
- set { loadAppDomainAssemblies = value; }
- }
+ public bool LoadAppDomainAssemblies { get; set; } = true;
/// Gets or sets assemblies loaded a startup in addition to those loaded in the AppDomain.
- public IList AssemblyNames
- {
- get { return assemblyNames; }
- set { assemblyNames = value; }
- }
+ public IList AssemblyNames { get; set; } = new List();
/// Gets the pattern for dlls that we know don't need to be investigated.
- public string AssemblySkipLoadingPattern
- {
- get { return assemblySkipLoadingPattern; }
- set { assemblySkipLoadingPattern = value; }
- }
+ public string AssemblySkipLoadingPattern { get; set; } = "^System|^mscorlib|^Microsoft|^AjaxControlToolkit|^Antlr3|^Autofac|^AutoMapper|^Castle|^ComponentArt|^CppCodeProvider|^DotNetOpenAuth|^EntityFramework|^EPPlus|^FluentValidation|^ImageResizer|^itextsharp|^log4net|^MaxMind|^MbUnit|^MiniProfiler|^Mono.Math|^MvcContrib|^Newtonsoft|^NHibernate|^nunit|^Org.Mentalis|^PerlRegex|^QuickGraph|^Recaptcha|^Remotion|^RestSharp|^Rhino|^Telerik|^Iesi|^TestDriven|^TestFu|^UserAgentStringLibrary|^VJSharpCodeProvider|^WebActivator|^WebDev|^WebGrease";
/// Gets or sets the pattern for dll that will be investigated. For ease of use this defaults to match all but to increase performance you might want to configure a pattern that includes assemblies and your own.
/// If you change this so that Nop assemblies aren't investigated (e.g. by not including something like "^Nop|..." you may break core functionality.
- public string AssemblyRestrictToLoadingPattern
- {
- get { return assemblyRestrictToLoadingPattern; }
- set { assemblyRestrictToLoadingPattern = value; }
- }
+ public string AssemblyRestrictToLoadingPattern { get; set; } = ".*";
#endregion
diff --git a/src/Libraries/Nop.Core/Infrastructure/INopFileProvider.cs b/src/Libraries/Nop.Core/Infrastructure/INopFileProvider.cs
new file mode 100644
index 00000000000..5dc826e3cd3
--- /dev/null
+++ b/src/Libraries/Nop.Core/Infrastructure/INopFileProvider.cs
@@ -0,0 +1,309 @@
+using System;
+using System.Collections.Generic;
+using System.Security.AccessControl;
+using System.Text;
+using Microsoft.Extensions.FileProviders;
+
+namespace Nop.Core.Infrastructure
+{
+ ///
+ /// A file provider abstraction
+ ///
+ public interface INopFileProvider : IFileProvider
+ {
+ ///
+ /// Combines an array of strings into a path
+ ///
+ /// An array of parts of the path
+ /// The combined paths
+ string Combine(params string[] paths);
+
+ ///
+ /// Creates all directories and subdirectories in the specified path unless they already exist
+ ///
+ /// The directory to create
+ void CreateDirectory(string path);
+
+ ///
+ /// Creates or overwrites a file in the specified path
+ ///
+ /// The path and name of the file to create
+ void CreateFile(string path);
+
+ ///
+ /// Depth-first recursive delete, with handling for descendant directories open in Windows Explorer.
+ ///
+ /// Directory path
+ void DeleteDirectory(string path);
+
+ ///
+ /// Deletes the specified file
+ ///
+ /// The name of the file to be deleted. Wildcard characters are not supported
+ void DeleteFile(string filePath);
+
+ ///
+ /// Determines whether the given path refers to an existing directory on disk
+ ///
+ /// The path to test
+ ///
+ /// true if path refers to an existing directory; false if the directory does not exist or an error occurs when
+ /// trying to determine if the specified file exists
+ ///
+ bool DirectoryExists(string path);
+
+ ///
+ /// Moves a file or a directory and its contents to a new location
+ ///
+ /// The path of the file or directory to move
+ ///
+ /// The path to the new location for sourceDirName. If sourceDirName is a file, then destDirName
+ /// must also be a file name
+ ///
+ void DirectoryMove(string sourceDirName, string destDirName);
+
+ ///
+ /// Returns an enumerable collection of file names that match a search pattern in
+ /// a specified path, and optionally searches subdirectories.
+ ///
+ /// The path to the directory to search
+ ///
+ /// The search string to match against the names of files in path. This parameter
+ /// can contain a combination of valid literal path and wildcard (* and ?) characters
+ /// , but doesn't support regular expressions.
+ ///
+ ///
+ /// Specifies whether to search the current directory, or the current directory and all
+ /// subdirectories
+ ///
+ ///
+ /// An enumerable collection of the full names (including paths) for the files in
+ /// the directory specified by path and that match the specified search pattern
+ ///
+ IEnumerable EnumerateFiles(string directoryPath, string searchPattern, bool topDirectoryOnly = true);
+
+ ///
+ /// Copies an existing file to a new file. Overwriting a file of the same name is allowed
+ ///
+ /// The file to copy
+ /// The name of the destination file. This cannot be a directory
+ /// true if the destination file can be overwritten; otherwise, false
+ void FileCopy(string sourceFileName, string destFileName, bool overwrite = false);
+
+ ///
+ /// Determines whether the specified file exists
+ ///
+ /// The file to check
+ ///
+ /// True if the caller has the required permissions and path contains the name of an existing file; otherwise,
+ /// false.
+ ///
+ bool FileExists(string filePath);
+
+ ///
+ /// Gets the length of the file in bytes, or -1 for a directory or non-existing files
+ ///
+ /// File path
+ /// The length of the file
+ long FileLength(string path);
+
+ ///
+ /// Moves a specified file to a new location, providing the option to specify a new file name
+ ///
+ /// The name of the file to move. Can include a relative or absolute path
+ /// The new path and name for the file
+ void FileMove(string sourceFileName, string destFileName);
+
+ ///
+ /// Returns the absolute path to the directory
+ ///
+ /// An array of parts of the path
+ /// The absolute path to the directory
+ string GetAbsolutePath(params string[] paths);
+
+ ///
+ /// Gets a System.Security.AccessControl.DirectorySecurity object that encapsulates the access control list (ACL) entries for a specified directory
+ ///
+ /// The path to a directory containing a System.Security.AccessControl.DirectorySecurity object that describes the file's access control list (ACL) information
+ /// An object that encapsulates the access control rules for the file described by the path parameter
+ DirectorySecurity GetAccessControl(string path);
+
+ ///
+ /// Returns the creation date and time of the specified file or directory
+ ///
+ /// The file or directory for which to obtain creation date and time information
+ ///
+ /// A System.DateTime structure set to the creation date and time for the specified file or directory. This value
+ /// is expressed in local time
+ ///
+ DateTime GetCreationTime(string path);
+
+ ///
+ /// Returns the names of the subdirectories (including their paths) that match the
+ /// specified search pattern in the specified directory
+ ///
+ /// The path to the directory to search
+ ///
+ /// The search string to match against the names of subdirectories in path. This
+ /// parameter can contain a combination of valid literal and wildcard characters
+ /// , but doesn't support regular expressions.
+ ///
+ ///
+ /// Specifies whether to search the current directory, or the current directory and all
+ /// subdirectories
+ ///
+ ///
+ /// An array of the full names (including paths) of the subdirectories that match
+ /// the specified criteria, or an empty array if no directories are found
+ ///
+ string[] GetDirectories(string path, string searchPattern = "", bool topDirectoryOnly = true);
+
+ ///
+ /// Returns the directory information for the specified path string
+ ///
+ /// The path of a file or directory
+ ///
+ /// Directory information for path, or null if path denotes a root directory or is null. Returns
+ /// System.String.Empty if path does not contain directory information
+ ///
+ string GetDirectoryName(string path);
+
+ ///
+ /// Returns the directory name only for the specified path string
+ ///
+ /// The path of directory
+ /// The directory name
+ string GetDirectoryNameOnly(string path);
+
+ ///
+ /// Returns the extension of the specified path string
+ ///
+ /// The path string from which to get the extension
+ /// The extension of the specified path (including the period ".")
+ string GetFileExtension(string filePath);
+
+ ///
+ /// Returns the file name and extension of the specified path string
+ ///
+ /// The path string from which to obtain the file name and extension
+ /// The characters after the last directory character in path
+ string GetFileName(string path);
+
+ ///
+ /// Returns the file name of the specified path string without the extension
+ ///
+ /// The path of the file
+ /// The file name, minus the last period (.) and all characters following it
+ string GetFileNameWithoutExtension(string filePath);
+
+ ///
+ /// Returns the names of files (including their paths) that match the specified search
+ /// pattern in the specified directory, using a value to determine whether to search subdirectories.
+ ///
+ /// The path to the directory to search
+ ///
+ /// The search string to match against the names of files in path. This parameter
+ /// can contain a combination of valid literal path and wildcard (* and ?) characters
+ /// , but doesn't support regular expressions.
+ ///
+ ///
+ /// Specifies whether to search the current directory, or the current directory and all
+ /// subdirectories
+ ///
+ ///
+ /// An array of the full names (including paths) for the files in the specified directory
+ /// that match the specified search pattern, or an empty array if no files are found.
+ ///
+ string[] GetFiles(string directoryPath, string searchPattern = "", bool topDirectoryOnly = true);
+
+ ///
+ /// Returns the date and time the specified file or directory was last accessed
+ ///
+ /// The file or directory for which to obtain access date and time information
+ /// A System.DateTime structure set to the date and time that the specified file
+ DateTime GetLastAccessTime(string path);
+
+ ///
+ /// Returns the date and time the specified file or directory was last written to
+ ///
+ /// The file or directory for which to obtain write date and time information
+ ///
+ /// A System.DateTime structure set to the date and time that the specified file or directory was last written to.
+ /// This value is expressed in local time
+ ///
+ DateTime GetLastWriteTime(string path);
+
+ ///
+ /// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last
+ /// written to
+ ///
+ /// The file or directory for which to obtain write date and time information
+ ///
+ /// A System.DateTime structure set to the date and time that the specified file or directory was last written to.
+ /// This value is expressed in UTC time
+ ///
+ DateTime GetLastWriteTimeUtc(string path);
+
+ ///
+ /// Retrieves the parent directory of the specified path
+ ///
+ /// The path for which to retrieve the parent directory
+ /// The parent directory, or null if path is the root directory, including the root of a UNC server or share name
+ string GetParentDirectory(string directoryPath);
+
+ ///
+ /// Checks if the path is directory
+ ///
+ /// Path for check
+ /// True, if the path is a directory, otherwise false
+ bool IsDirectory(string path);
+
+ ///
+ /// Maps a virtual path to a physical disk path.
+ ///
+ /// The path to map. E.g. "~/bin"
+ /// The physical path. E.g. "c:\inetpub\wwwroot\bin"
+ string MapPath(string path);
+
+ ///
+ /// Reads the contents of the file into a byte array
+ ///
+ /// The file for reading
+ /// A byte array containing the contents of the file
+ byte[] ReadAllBytes(string filePath);
+
+ ///
+ /// Opens a file, reads all lines of the file with the specified encoding, and then closes the file.
+ ///
+ /// The file to open for reading
+ /// The encoding applied to the contents of the file
+ /// A string containing all lines of the file
+ string ReadAllText(string path, Encoding encoding);
+
+ ///
+ /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to
+ ///
+ /// The file for which to set the date and time information
+ ///
+ /// A System.DateTime containing the value to set for the last write date and time of path.
+ /// This value is expressed in UTC time
+ ///
+ void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc);
+
+ ///
+ /// Writes the specified byte array to the file
+ ///
+ /// The file to write to
+ /// The bytes to write to the file
+ void WriteAllBytes(string filePath, byte[] bytes);
+
+ ///
+ /// Creates a new file, writes the specified string to the file using the specified encoding,
+ /// and then closes the file. If the target file already exists, it is overwritten.
+ ///
+ /// The file to write to
+ /// The string to write to the file
+ /// The encoding to apply to the string
+ void WriteAllText(string path, string contents, Encoding encoding);
+ }
+}
\ No newline at end of file
diff --git a/src/Libraries/Nop.Core/Infrastructure/NopEngine.cs b/src/Libraries/Nop.Core/Infrastructure/NopEngine.cs
index d134f243a53..d2600d0af06 100644
--- a/src/Libraries/Nop.Core/Infrastructure/NopEngine.cs
+++ b/src/Libraries/Nop.Core/Infrastructure/NopEngine.cs
@@ -147,13 +147,12 @@ public void Initialize(IServiceCollection services)
//most of API providers require TLS 1.2 nowadays
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
- //set base application path
var provider = services.BuildServiceProvider();
var hostingEnvironment = provider.GetRequiredService();
- var nopConfig = provider.GetRequiredService();
- CommonHelper.BaseDirectory = hostingEnvironment.ContentRootPath;
+ CommonHelper.DefaultFileProvider = new NopFileProvider(hostingEnvironment);
//initialize plugins
+ var nopConfig = provider.GetRequiredService();
var mvcCoreBuilder = services.AddMvcCore();
PluginManager.Initialize(mvcCoreBuilder.PartManager, nopConfig);
}
@@ -208,7 +207,8 @@ public IServiceProvider ConfigureServices(IServiceCollection services, IConfigur
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
//set App_Data path as base data directory (required to create and save SQL Server Compact database file in App_Data folder)
- AppDomain.CurrentDomain.SetData("DataDirectory", CommonHelper.MapPath("~/App_Data/"));
+ var fileProvider = Resolve();
+ AppDomain.CurrentDomain.SetData("DataDirectory", fileProvider.MapPath("~/App_Data/"));
return _serviceProvider;
}
diff --git a/src/Libraries/Nop.Core/Infrastructure/NopFileProvider.cs b/src/Libraries/Nop.Core/Infrastructure/NopFileProvider.cs
new file mode 100644
index 00000000000..4c28faf39cd
--- /dev/null
+++ b/src/Libraries/Nop.Core/Infrastructure/NopFileProvider.cs
@@ -0,0 +1,499 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Security.AccessControl;
+using System.Text;
+using System.Threading;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.FileProviders;
+
+namespace Nop.Core.Infrastructure
+{
+ ///
+ /// IO functions using the on-disk file system
+ ///
+ public class NopFileProvider : PhysicalFileProvider, INopFileProvider
+ {
+ ///
+ /// Initializes a new instance of a NopFileProvider
+ ///
+ /// Hosting environment
+ public NopFileProvider(IHostingEnvironment hostingEnvironment)
+ : base(File.Exists(hostingEnvironment.WebRootPath) ? Path.GetDirectoryName(hostingEnvironment.WebRootPath) : hostingEnvironment.WebRootPath)
+ {
+ var path = hostingEnvironment.ContentRootPath ?? string.Empty;
+ if (File.Exists(path))
+ path = Path.GetDirectoryName(path);
+
+ BaseDirectory = path;
+ }
+
+ #region Utilities
+
+ private static void DeleteDirectoryRecursive(string path)
+ {
+ Directory.Delete(path, true);
+ const int maxIterationToWait = 10;
+ var curIteration = 0;
+
+ //according to the documentation(https://msdn.microsoft.com/ru-ru/library/windows/desktop/aa365488.aspx)
+ //System.IO.Directory.Delete method ultimately (after removing the files) calls native
+ //RemoveDirectory function which marks the directory as "deleted". That's why we wait until
+ //the directory is actually deleted. For more details see https://stackoverflow.com/a/4245121
+ while (Directory.Exists(path))
+ {
+ curIteration += 1;
+ if (curIteration > maxIterationToWait)
+ return;
+ Thread.Sleep(100);
+ }
+ }
+
+ #endregion
+
+ ///
+ /// Combines an array of strings into a path
+ ///
+ /// An array of parts of the path
+ /// The combined paths
+ public virtual string Combine(params string[] paths)
+ {
+ return Path.Combine(paths);
+ }
+
+ ///
+ /// Creates all directories and subdirectories in the specified path unless they already exist
+ ///
+ /// The directory to create
+ public virtual void CreateDirectory(string path)
+ {
+ if (!DirectoryExists(path))
+ Directory.CreateDirectory(path);
+ }
+
+ ///
+ /// Creates or overwrites a file in the specified path
+ ///
+ /// The path and name of the file to create
+ public virtual void CreateFile(string path)
+ {
+ if (FileExists(path))
+ return;
+
+ //we use 'using' to close the file after it's created
+ using (File.Create(path)) { }
+ }
+
+ ///
+ /// Depth-first recursive delete, with handling for descendant directories open in Windows Explorer.
+ ///
+ /// Directory path
+ public void DeleteDirectory(string path)
+ {
+ if (string.IsNullOrEmpty(path))
+ throw new ArgumentNullException(path);
+
+ //find more info about directory deletion
+ //and why we use this approach at https://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true
+
+ foreach (var directory in Directory.GetDirectories(path))
+ {
+ DeleteDirectory(directory);
+ }
+
+ try
+ {
+ DeleteDirectoryRecursive(path);
+ }
+ catch (IOException)
+ {
+ DeleteDirectoryRecursive(path);
+ }
+ catch (UnauthorizedAccessException)
+ {
+ DeleteDirectoryRecursive(path);
+ }
+ }
+
+
+ ///
+ /// Deletes the specified file
+ ///
+ /// The name of the file to be deleted. Wildcard characters are not supported
+ public virtual void DeleteFile(string filePath)
+ {
+ if (!FileExists(filePath))
+ return;
+
+ File.Delete(filePath);
+ }
+
+ ///
+ /// Determines whether the given path refers to an existing directory on disk
+ ///
+ /// The path to test
+ ///
+ /// true if path refers to an existing directory; false if the directory does not exist or an error occurs when
+ /// trying to determine if the specified file exists
+ ///
+ public virtual bool DirectoryExists(string path)
+ {
+ return Directory.Exists(path);
+ }
+
+ ///
+ /// Moves a file or a directory and its contents to a new location
+ ///
+ /// The path of the file or directory to move
+ ///
+ /// The path to the new location for sourceDirName. If sourceDirName is a file, then destDirName
+ /// must also be a file name
+ ///
+ public virtual void DirectoryMove(string sourceDirName, string destDirName)
+ {
+ Directory.Move(sourceDirName, destDirName);
+ }
+
+ ///
+ /// Returns an enumerable collection of file names that match a search pattern in
+ /// a specified path, and optionally searches subdirectories.
+ ///
+ /// The path to the directory to search
+ ///
+ /// The search string to match against the names of files in path. This parameter
+ /// can contain a combination of valid literal path and wildcard (* and ?) characters
+ /// , but doesn't support regular expressions.
+ ///
+ ///
+ /// Specifies whether to search the current directory, or the current directory and all
+ /// subdirectories
+ ///
+ ///
+ /// An enumerable collection of the full names (including paths) for the files in
+ /// the directory specified by path and that match the specified search pattern
+ ///
+ public virtual IEnumerable EnumerateFiles(string directoryPath, string searchPattern,
+ bool topDirectoryOnly = true)
+ {
+ return Directory.EnumerateFiles(directoryPath, searchPattern,
+ topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories);
+ }
+
+ ///
+ /// Copies an existing file to a new file. Overwriting a file of the same name is allowed
+ ///
+ /// The file to copy
+ /// The name of the destination file. This cannot be a directory
+ /// true if the destination file can be overwritten; otherwise, false
+ public virtual void FileCopy(string sourceFileName, string destFileName, bool overwrite = false)
+ {
+ File.Copy(sourceFileName, destFileName, overwrite);
+ }
+
+ ///
+ /// Determines whether the specified file exists
+ ///
+ /// The file to check
+ ///
+ /// True if the caller has the required permissions and path contains the name of an existing file; otherwise,
+ /// false.
+ ///
+ public virtual bool FileExists(string filePath)
+ {
+ return File.Exists(filePath);
+ }
+
+ ///
+ /// Gets the length of the file in bytes, or -1 for a directory or non-existing files
+ ///
+ /// File path
+ /// The length of the file
+ public virtual long FileLength(string path)
+ {
+ if (!FileExists(path))
+ return -1;
+
+ return new FileInfo(path).Length;
+ }
+
+ ///
+ /// Moves a specified file to a new location, providing the option to specify a new file name
+ ///
+ /// The name of the file to move. Can include a relative or absolute path
+ /// The new path and name for the file
+ public virtual void FileMove(string sourceFileName, string destFileName)
+ {
+ File.Move(sourceFileName, destFileName);
+ }
+
+ ///
+ /// Returns the absolute path to the directory
+ ///
+ /// An array of parts of the path
+ /// The absolute path to the directory
+ public virtual string GetAbsolutePath(params string[] paths)
+ {
+ var allPaths = paths.ToList();
+ allPaths.Insert(0, Root);
+
+ return Path.Combine(allPaths.ToArray());
+ }
+
+ ///
+ /// Gets a System.Security.AccessControl.DirectorySecurity object that encapsulates the access control list (ACL) entries for a specified directory
+ ///
+ /// The path to a directory containing a System.Security.AccessControl.DirectorySecurity object that describes the file's access control list (ACL) information
+ /// An object that encapsulates the access control rules for the file described by the path parameter
+ public virtual DirectorySecurity GetAccessControl(string path)
+ {
+ return Directory.GetAccessControl(path);
+ }
+
+ ///
+ /// Returns the creation date and time of the specified file or directory
+ ///
+ /// The file or directory for which to obtain creation date and time information
+ ///
+ /// A System.DateTime structure set to the creation date and time for the specified file or directory. This value
+ /// is expressed in local time
+ ///
+ public virtual DateTime GetCreationTime(string path)
+ {
+ return File.GetCreationTime(path);
+ }
+
+ ///
+ /// Returns the names of the subdirectories (including their paths) that match the
+ /// specified search pattern in the specified directory
+ ///
+ /// The path to the directory to search
+ ///
+ /// The search string to match against the names of subdirectories in path. This
+ /// parameter can contain a combination of valid literal and wildcard characters
+ /// , but doesn't support regular expressions.
+ ///
+ ///
+ /// Specifies whether to search the current directory, or the current directory and all
+ /// subdirectories
+ ///
+ ///
+ /// An array of the full names (including paths) of the subdirectories that match
+ /// the specified criteria, or an empty array if no directories are found
+ ///
+ public virtual string[] GetDirectories(string path, string searchPattern = "", bool topDirectoryOnly = true)
+ {
+ if (string.IsNullOrEmpty(searchPattern))
+ searchPattern = "*";
+
+ return Directory.GetDirectories(path, searchPattern,
+ topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories);
+ }
+
+ ///
+ /// Returns the directory information for the specified path string
+ ///
+ /// The path of a file or directory
+ ///
+ /// Directory information for path, or null if path denotes a root directory or is null. Returns
+ /// System.String.Empty if path does not contain directory information
+ ///
+ public virtual string GetDirectoryName(string path)
+ {
+ return Path.GetDirectoryName(path);
+ }
+
+ ///
+ /// Returns the directory name only for the specified path string
+ ///
+ /// The path of directory
+ /// The directory name
+ public virtual string GetDirectoryNameOnly(string path)
+ {
+ return new DirectoryInfo(path).Name;
+ }
+
+ ///
+ /// Returns the extension of the specified path string
+ ///
+ /// The path string from which to get the extension
+ /// The extension of the specified path (including the period ".")
+ public virtual string GetFileExtension(string filePath)
+ {
+ return Path.GetExtension(filePath);
+ }
+
+ ///
+ /// Returns the file name and extension of the specified path string
+ ///
+ /// The path string from which to obtain the file name and extension
+ /// The characters after the last directory character in path
+ public virtual string GetFileName(string path)
+ {
+ return Path.GetFileName(path);
+ }
+
+ ///
+ /// Returns the file name of the specified path string without the extension
+ ///
+ /// The path of the file
+ /// The file name, minus the last period (.) and all characters following it
+ public virtual string GetFileNameWithoutExtension(string filePath)
+ {
+ return Path.GetFileNameWithoutExtension(filePath);
+ }
+
+ ///
+ /// Returns the names of files (including their paths) that match the specified search
+ /// pattern in the specified directory, using a value to determine whether to search subdirectories.
+ ///
+ /// The path to the directory to search
+ ///
+ /// The search string to match against the names of files in path. This parameter
+ /// can contain a combination of valid literal path and wildcard (* and ?) characters
+ /// , but doesn't support regular expressions.
+ ///
+ ///
+ /// Specifies whether to search the current directory, or the current directory and all
+ /// subdirectories
+ ///
+ ///
+ /// An array of the full names (including paths) for the files in the specified directory
+ /// that match the specified search pattern, or an empty array if no files are found.
+ ///
+ public virtual string[] GetFiles(string directoryPath, string searchPattern = "", bool topDirectoryOnly = true)
+ {
+ if (string.IsNullOrEmpty(searchPattern))
+ searchPattern = "*.*";
+
+ return Directory.GetFiles(directoryPath, searchPattern,
+ topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories);
+ }
+
+ ///
+ /// Returns the date and time the specified file or directory was last accessed
+ ///
+ /// The file or directory for which to obtain access date and time information
+ /// A System.DateTime structure set to the date and time that the specified file
+ public virtual DateTime GetLastAccessTime(string path)
+ {
+ return File.GetLastAccessTime(path);
+ }
+
+ ///
+ /// Returns the date and time the specified file or directory was last written to
+ ///
+ /// The file or directory for which to obtain write date and time information
+ ///
+ /// A System.DateTime structure set to the date and time that the specified file or directory was last written to.
+ /// This value is expressed in local time
+ ///
+ public virtual DateTime GetLastWriteTime(string path)
+ {
+ return File.GetLastWriteTime(path);
+ }
+
+ ///
+ /// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last
+ /// written to
+ ///
+ /// The file or directory for which to obtain write date and time information
+ ///
+ /// A System.DateTime structure set to the date and time that the specified file or directory was last written to.
+ /// This value is expressed in UTC time
+ ///
+ public virtual DateTime GetLastWriteTimeUtc(string path)
+ {
+ return File.GetLastWriteTimeUtc(path);
+ }
+
+ ///
+ /// Retrieves the parent directory of the specified path
+ ///
+ /// The path for which to retrieve the parent directory
+ /// The parent directory, or null if path is the root directory, including the root of a UNC server or share name
+ public virtual string GetParentDirectory(string directoryPath)
+ {
+ return Directory.GetParent(directoryPath).FullName;
+ }
+
+ ///
+ /// Checks if the path is directory
+ ///
+ /// Path for check
+ /// True, if the path is a directory, otherwise false
+ public virtual bool IsDirectory(string path)
+ {
+ return DirectoryExists(path);
+ }
+
+ ///
+ /// Maps a virtual path to a physical disk path.
+ ///
+ /// The path to map. E.g. "~/bin"
+ /// The physical path. E.g. "c:\inetpub\wwwroot\bin"
+ public virtual string MapPath(string path)
+ {
+ path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\');
+ return Path.Combine(BaseDirectory ?? string.Empty, path);
+ }
+
+ ///
+ /// Reads the contents of the file into a byte array
+ ///
+ /// The file for reading
+ /// A byte array containing the contents of the file
+ public virtual byte[] ReadAllBytes(string filePath)
+ {
+ return File.Exists(filePath) ? File.ReadAllBytes(filePath) : new byte[0];
+ }
+
+ ///
+ /// Opens a file, reads all lines of the file with the specified encoding, and then closes the file.
+ ///
+ /// The file to open for reading
+ /// The encoding applied to the contents of the file
+ /// A string containing all lines of the file
+ public virtual string ReadAllText(string path, Encoding encoding)
+ {
+ return File.ReadAllText(path, encoding);
+ }
+
+ ///
+ /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to
+ ///
+ /// The file for which to set the date and time information
+ ///
+ /// A System.DateTime containing the value to set for the last write date and time of path.
+ /// This value is expressed in UTC time
+ ///
+ public virtual void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
+ {
+ File.SetLastWriteTimeUtc(path, lastWriteTimeUtc);
+ }
+
+ ///
+ /// Writes the specified byte array to the file
+ ///
+ /// The file to write to
+ /// The bytes to write to the file
+ public virtual void WriteAllBytes(string filePath, byte[] bytes)
+ {
+ File.WriteAllBytes(filePath, bytes);
+ }
+
+ ///
+ /// Creates a new file, writes the specified string to the file using the specified encoding,
+ /// and then closes the file. If the target file already exists, it is overwritten.
+ ///
+ /// The file to write to
+ /// The string to write to the file
+ /// The encoding to apply to the string
+ public virtual void WriteAllText(string path, string contents, Encoding encoding)
+ {
+ File.WriteAllText(path, contents, encoding);
+ }
+
+ protected string BaseDirectory { get; }
+ }
+}
\ No newline at end of file
diff --git a/src/Libraries/Nop.Core/Infrastructure/WebAppTypeFinder.cs b/src/Libraries/Nop.Core/Infrastructure/WebAppTypeFinder.cs
index a659e40fc39..f18a903f30f 100644
--- a/src/Libraries/Nop.Core/Infrastructure/WebAppTypeFinder.cs
+++ b/src/Libraries/Nop.Core/Infrastructure/WebAppTypeFinder.cs
@@ -1,4 +1,5 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
using System.Reflection;
namespace Nop.Core.Infrastructure
@@ -16,6 +17,14 @@ public class WebAppTypeFinder : AppDomainTypeFinder
#endregion
+ #region Ctor
+
+ public WebAppTypeFinder(INopFileProvider fileProvider = null) : base(fileProvider)
+ {
+ }
+
+ #endregion
+
#region Properties
///
@@ -37,7 +46,7 @@ public bool EnsureBinFolderAssembliesLoaded
/// The physical path. E.g. "c:\inetpub\wwwroot\bin"
public virtual string GetBinDirectory()
{
- return System.AppContext.BaseDirectory;
+ return AppContext.BaseDirectory;
}
///
diff --git a/src/Libraries/Nop.Core/Plugins/PluginDescriptor.cs b/src/Libraries/Nop.Core/Plugins/PluginDescriptor.cs
index d7554a3c7af..97cac537665 100644
--- a/src/Libraries/Nop.Core/Plugins/PluginDescriptor.cs
+++ b/src/Libraries/Nop.Core/Plugins/PluginDescriptor.cs
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
-using System.IO;
using System.Reflection;
using Newtonsoft.Json;
using Nop.Core.Infrastructure;
@@ -200,7 +199,7 @@ public override int GetHashCode()
/// Gets or sets the original assembly file that a shadow copy was made from it
///
[JsonIgnore]
- public virtual FileInfo OriginalAssemblyFile { get; internal set; }
+ public virtual string OriginalAssemblyFile { get; internal set; }
///
/// Gets or sets the assembly that has been shadow copied that is active in the application
diff --git a/src/Libraries/Nop.Core/Plugins/PluginExtensions.cs b/src/Libraries/Nop.Core/Plugins/PluginExtensions.cs
index bf99b632ecf..8647f73f27e 100644
--- a/src/Libraries/Nop.Core/Plugins/PluginExtensions.cs
+++ b/src/Libraries/Nop.Core/Plugins/PluginExtensions.cs
@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
-using System.IO;
using System.Linq;
+using Nop.Core.Infrastructure;
namespace Nop.Core.Plugins
{
@@ -31,18 +31,21 @@ public static string GetLogoUrl(this PluginDescriptor pluginDescriptor, IWebHelp
if (webHelper == null)
throw new ArgumentNullException(nameof(webHelper));
- if (pluginDescriptor.OriginalAssemblyFile == null || pluginDescriptor.OriginalAssemblyFile.Directory == null)
+ var fileProvider = EngineContext.Current.Resolve();
+
+ var pluginDirectory = fileProvider.GetDirectoryName(pluginDescriptor.OriginalAssemblyFile);
+
+ if (string.IsNullOrEmpty(pluginDirectory))
{
return null;
}
- var pluginDirectory = pluginDescriptor.OriginalAssemblyFile.Directory;
-
- var logoExtension = SupportedLogoImageExtensions.FirstOrDefault(ext => File.Exists(Path.Combine(pluginDirectory.FullName, "logo." + ext)));
+ var logoExtension = SupportedLogoImageExtensions.FirstOrDefault(ext => fileProvider.FileExists(fileProvider.Combine(pluginDirectory, "logo." + ext)));
- if (string.IsNullOrWhiteSpace(logoExtension)) return null; //No logo file was found with any of the supported extensions.
+ if (string.IsNullOrWhiteSpace(logoExtension))
+ return null; //No logo file was found with any of the supported extensions.
- var logoUrl = $"{webHelper.GetStoreLocation()}plugins/{pluginDirectory.Name}/logo.{logoExtension}";
+ var logoUrl = $"{webHelper.GetStoreLocation()}plugins/{fileProvider.GetDirectoryNameOnly(pluginDirectory)}/logo.{logoExtension}";
return logoUrl;
}
}
diff --git a/src/Libraries/Nop.Core/Plugins/PluginManager.cs b/src/Libraries/Nop.Core/Plugins/PluginManager.cs
index d2d28ffdeed..4d29fca5a47 100644
--- a/src/Libraries/Nop.Core/Plugins/PluginManager.cs
+++ b/src/Libraries/Nop.Core/Plugins/PluginManager.cs
@@ -4,11 +4,13 @@
using System.IO;
using System.Linq;
using System.Reflection;
+using System.Text;
using System.Threading;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Newtonsoft.Json;
using Nop.Core.ComponentModel;
using Nop.Core.Configuration;
+using Nop.Core.Infrastructure;
//Contributor: Umbraco (http://www.umbraco.com). Thanks a lot!
//SEE THIS POST for full details of what this does - http://shazwazza.com/post/Developing-a-plugin-framework-in-ASPNET-with-medium-trust.aspx
@@ -30,9 +32,10 @@ public class PluginManager
#region Fields
private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim();
- private static DirectoryInfo _shadowCopyFolder;
- private static readonly List BaseAppLibraries;
- private static DirectoryInfo _reserveShadowCopyFolder;
+ private static string _shadowCopyFolder;
+ private static readonly List _baseAppLibraries;
+ private static string _reserveShadowCopyFolder;
+ private static readonly INopFileProvider _fileProvider;
#endregion
@@ -40,18 +43,20 @@ public class PluginManager
static PluginManager()
{
+ //we use the default file provider, since the DI isn't initialized yet
+ _fileProvider = CommonHelper.DefaultFileProvider;
+
//get all libraries from /bin/{version}/ directory
- BaseAppLibraries = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory)
- .GetFiles("*.dll", SearchOption.TopDirectoryOnly).Select(fi => fi.Name).ToList();
+ _baseAppLibraries =_fileProvider.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll").Select(fi => _fileProvider.GetFileName(fi)).ToList();
//get all libraries from base site directory
if(!AppDomain.CurrentDomain.BaseDirectory.Equals(Environment.CurrentDirectory, StringComparison.InvariantCultureIgnoreCase))
- BaseAppLibraries.AddRange(new DirectoryInfo(Environment.CurrentDirectory).GetFiles("*.dll", SearchOption.TopDirectoryOnly).Select(fi => fi.Name));
+ _baseAppLibraries.AddRange(_fileProvider.GetFiles(Environment.CurrentDirectory, "*.dll").Select(fi => _fileProvider.GetFileName(fi)));
//get all libraries from refs directory
- var refsPathName = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, RefsPathName));
- if(refsPathName.Exists)
- BaseAppLibraries.AddRange(refsPathName.GetFiles("*.dll", SearchOption.TopDirectoryOnly).Select(fi => fi.Name));
+ var refsPathName = _fileProvider.Combine(Environment.CurrentDirectory, RefsPathName);
+ if(_fileProvider.DirectoryExists(refsPathName))
+ _baseAppLibraries.AddRange(_fileProvider.GetFiles(refsPathName, "*.dll").Select(fi => _fileProvider.GetFileName(fi)));
}
#endregion
@@ -63,25 +68,25 @@ static PluginManager()
///
/// Plugin directory info
/// Original and parsed description files
- private static IEnumerable> GetDescriptionFilesAndDescriptors(DirectoryInfo pluginFolder)
+ private static IEnumerable> GetDescriptionFilesAndDescriptors(string pluginFolder)
{
if (pluginFolder == null)
throw new ArgumentNullException(nameof(pluginFolder));
//create list ()
- var result = new List>();
+ var result = new List>();
//add display order and path to list
- foreach (var descriptionFile in pluginFolder.GetFiles(PluginDescriptionFileName, SearchOption.AllDirectories))
+ foreach (var descriptionFile in _fileProvider.GetFiles(pluginFolder, PluginDescriptionFileName, false))
{
- if (!IsPackagePluginFolder(descriptionFile.Directory))
+ if (!IsPackagePluginFolder(_fileProvider.GetDirectoryName(descriptionFile)))
continue;
//parse file
- var pluginDescriptor = GetPluginDescriptorFromFile(descriptionFile.FullName);
+ var pluginDescriptor = GetPluginDescriptorFromFile(descriptionFile);
//populate list
- result.Add(new KeyValuePair(descriptionFile, pluginDescriptor));
+ result.Add(new KeyValuePair(descriptionFile, pluginDescriptor));
}
//sort list by display order. NOTE: Lowest DisplayOrder will be first i.e 0 , 1, 1, 1, 5, 10
@@ -98,16 +103,16 @@ private static IEnumerable> GetDescript
private static IList GetInstalledPluginNames(string filePath)
{
//check whether file exists
- if (!File.Exists(filePath))
+ if (!_fileProvider.FileExists(filePath))
{
//if not, try to parse the file that was used in previous nopCommerce versions
- filePath = CommonHelper.MapPath(ObsoleteInstalledPluginsFilePath);
- if (!File.Exists(filePath))
+ filePath = _fileProvider.MapPath(ObsoleteInstalledPluginsFilePath);
+ if (!_fileProvider.FileExists(filePath))
return new List();
//get plugin system names from the old txt file
var pluginSystemNames = new List();
- using (var reader = new StringReader(File.ReadAllText(filePath)))
+ using (var reader = new StringReader(_fileProvider.ReadAllText(filePath, Encoding.UTF8)))
{
string pluginName;
while ((pluginName = reader.ReadLine()) != null)
@@ -118,15 +123,15 @@ private static IList GetInstalledPluginNames(string filePath)
}
//save system names of installed plugins to the new file
- SaveInstalledPluginNames(pluginSystemNames, CommonHelper.MapPath(InstalledPluginsFilePath));
+ SaveInstalledPluginNames(pluginSystemNames, _fileProvider.MapPath(InstalledPluginsFilePath));
//and delete the old one
- File.Delete(filePath);
+ _fileProvider.DeleteFile(filePath);
return pluginSystemNames;
}
- var text = File.ReadAllText(filePath);
+ var text = _fileProvider.ReadAllText(filePath, Encoding.UTF8);
if (string.IsNullOrEmpty(text))
return new List();
@@ -143,23 +148,23 @@ private static void SaveInstalledPluginNames(IList pluginSystemNames, st
{
//save the file
var text = JsonConvert.SerializeObject(pluginSystemNames, Formatting.Indented);
- File.WriteAllText(filePath, text);
+ _fileProvider.WriteAllText(filePath, text, Encoding.UTF8);
}
///
/// Indicates whether assembly file is already loaded
///
- /// File info
- /// Result
- private static bool IsAlreadyLoaded(FileInfo fileInfo)
+ /// File path
+ /// True if assembly file is already loaded; otherwise false
+ private static bool IsAlreadyLoaded(string filePath)
{
//search library file name in base directory to ignore already existing (loaded) libraries
//(we do it because not all libraries are loaded immediately after application start)
- if (BaseAppLibraries.Any(sli => sli.Equals(fileInfo.Name, StringComparison.InvariantCultureIgnoreCase)))
+ if (_baseAppLibraries.Any(sli => sli.Equals(_fileProvider.GetFileName(filePath), StringComparison.InvariantCultureIgnoreCase)))
return true;
//compare full assembly name
- //var fileAssemblyName = AssemblyName.GetAssemblyName(fileInfo.FullName);
+ //var fileAssemblyName = AssemblyName.GetAssemblyName(filePath);
//foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
//{
// if (a.FullName.Equals(fileAssemblyName.FullName, StringComparison.InvariantCultureIgnoreCase))
@@ -170,9 +175,9 @@ private static bool IsAlreadyLoaded(FileInfo fileInfo)
//do not compare the full assembly name, just filename
try
{
- var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileInfo.FullName);
+ var fileNameWithoutExt = _fileProvider.GetFileNameWithoutExtension(filePath);
if (string.IsNullOrEmpty(fileNameWithoutExt))
- throw new Exception($"Cannot get file extension for {fileInfo.Name}");
+ throw new Exception($"Cannot get file extension for {_fileProvider.GetFileName(filePath)}");
foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
{
@@ -196,20 +201,22 @@ private static bool IsAlreadyLoaded(FileInfo fileInfo)
/// Config
/// Shadow copy path
/// Assembly
- private static Assembly PerformFileDeploy(FileInfo plug, ApplicationPartManager applicationPartManager, NopConfig config, string shadowCopyPath="")
+ private static Assembly PerformFileDeploy(string plug, ApplicationPartManager applicationPartManager, NopConfig config, string shadowCopyPath="")
{
- if (plug.Directory?.Parent == null)
- throw new InvalidOperationException($"The plugin directory for the {plug.Name} file exists in a folder outside of the allowed nopCommerce folder hierarchy");
+ var parent = string.IsNullOrEmpty(plug) ? string.Empty : _fileProvider.GetParentDirectory(plug);
+
+ if (string.IsNullOrEmpty(parent))
+ throw new InvalidOperationException($"The plugin directory for the {_fileProvider.GetFileName(plug)} file exists in a folder outside of the allowed nopCommerce folder hierarchy");
if (!config.UsePluginsShadowCopy)
return RegisterPluginDefinition(config, applicationPartManager, plug);
//in order to avoid possible issues we still copy libraries into ~/Plugins/bin/ directory
if (string.IsNullOrEmpty(shadowCopyPath))
- shadowCopyPath = _shadowCopyFolder.FullName;
+ shadowCopyPath = _shadowCopyFolder;
- var shadowCopyPlugFolder = Directory.CreateDirectory(shadowCopyPath);
- var shadowCopiedPlug = ShadowCopyFile(plug, shadowCopyPlugFolder);
+ _fileProvider.CreateDirectory(shadowCopyPath);
+ var shadowCopiedPlug = ShadowCopyFile(plug, shadowCopyPath);
Assembly shadowCopiedAssembly = null;
@@ -219,11 +226,11 @@ private static Assembly PerformFileDeploy(FileInfo plug, ApplicationPartManager
}
catch (FileLoadException)
{
- if (!config.CopyLockedPluginAssembilesToSubdirectoriesOnStartup || !shadowCopyPath.Equals(_shadowCopyFolder.FullName))
+ if (!config.CopyLockedPluginAssembilesToSubdirectoriesOnStartup || !shadowCopyPath.Equals(_shadowCopyFolder))
throw;
}
- return shadowCopiedAssembly ?? PerformFileDeploy(plug, applicationPartManager, config, _reserveShadowCopyFolder.FullName);
+ return shadowCopiedAssembly ?? PerformFileDeploy(plug, applicationPartManager, config, _reserveShadowCopyFolder);
}
///
@@ -232,11 +239,11 @@ private static Assembly PerformFileDeploy(FileInfo plug, ApplicationPartManager
/// Config
/// Application part manager
/// Plugin file info
- ///
- private static Assembly RegisterPluginDefinition(NopConfig config, ApplicationPartManager applicationPartManager, FileInfo plug)
+ /// Assembly
+ private static Assembly RegisterPluginDefinition(NopConfig config, ApplicationPartManager applicationPartManager, string plug)
{
//we can now register the plugin definition
- var assemblyName = AssemblyName.GetAssemblyName(plug.FullName);
+ var assemblyName = AssemblyName.GetAssemblyName(plug);
Assembly pluginAssembly;
try
{
@@ -252,7 +259,7 @@ private static Assembly RegisterPluginDefinition(NopConfig config, ApplicationPa
//you can use the UnsafeLoadFrom method to load a local assembly that the operating system has flagged as
//having been loaded from the web.
//see http://go.microsoft.com/fwlink/?LinkId=155569 for more information.
- pluginAssembly = Assembly.UnsafeLoadFrom(plug.FullName);
+ pluginAssembly = Assembly.UnsafeLoadFrom(plug);
}
else
{
@@ -269,23 +276,23 @@ private static Assembly RegisterPluginDefinition(NopConfig config, ApplicationPa
///
/// Copy the plugin file to shadow copy directory
///
- ///
- ///
- ///
- private static FileInfo ShadowCopyFile(FileInfo plug, DirectoryInfo shadowCopyPlugFolder)
+ /// Plugin file path
+ /// Path to shadow copy folder
+ /// File path to shadow copy of plugin file
+ private static string ShadowCopyFile(string pluginFilePath, string shadowCopyPlugFolder)
{
var shouldCopy = true;
- var shadowCopiedPlug = new FileInfo(Path.Combine(shadowCopyPlugFolder.FullName, plug.Name));
+ var shadowCopiedPlug = _fileProvider.Combine(shadowCopyPlugFolder, _fileProvider.GetFileName(pluginFilePath));
//check if a shadow copied file already exists and if it does, check if it's updated, if not don't copy
- if (shadowCopiedPlug.Exists)
+ if (_fileProvider.FileExists(shadowCopiedPlug))
{
//it's better to use LastWriteTimeUTC, but not all file systems have this property
//maybe it is better to compare file hash?
- var areFilesIdentical = shadowCopiedPlug.CreationTimeUtc.Ticks >= plug.CreationTimeUtc.Ticks;
+ var areFilesIdentical = _fileProvider.GetCreationTime(shadowCopiedPlug).ToUniversalTime().Ticks >= _fileProvider.GetCreationTime(pluginFilePath).ToUniversalTime().Ticks;
if (areFilesIdentical)
{
- Debug.WriteLine("Not copying; files appear identical: '{0}'", shadowCopiedPlug.Name);
+ Debug.WriteLine("Not copying; files appear identical: '{0}'", _fileProvider.GetFileName(shadowCopiedPlug));
shouldCopy = false;
}
else
@@ -293,8 +300,8 @@ private static FileInfo ShadowCopyFile(FileInfo plug, DirectoryInfo shadowCopyPl
//delete an existing file
//More info: https://www.nopcommerce.com/boards/t/11511/access-error-nopplugindiscountrulesbillingcountrydll.aspx?p=4#60838
- Debug.WriteLine("New plugin found; Deleting the old file: '{0}'", shadowCopiedPlug.Name);
- File.Delete(shadowCopiedPlug.FullName);
+ Debug.WriteLine("New plugin found; Deleting the old file: '{0}'", _fileProvider.GetFileName(shadowCopiedPlug));
+ _fileProvider.DeleteFile(shadowCopiedPlug);
}
}
@@ -303,25 +310,25 @@ private static FileInfo ShadowCopyFile(FileInfo plug, DirectoryInfo shadowCopyPl
try
{
- File.Copy(plug.FullName, shadowCopiedPlug.FullName, true);
+ _fileProvider.FileCopy(pluginFilePath, shadowCopiedPlug, true);
}
catch (IOException)
{
- Debug.WriteLine(shadowCopiedPlug.FullName + " is locked, attempting to rename");
+ Debug.WriteLine(shadowCopiedPlug + " is locked, attempting to rename");
//this occurs when the files are locked,
//for some reason devenv locks plugin files some times and for another crazy reason you are allowed to rename them
//which releases the lock, so that it what we are doing here, once it's renamed, we can re-shadow copy
try
{
- var oldFile = shadowCopiedPlug.FullName + Guid.NewGuid().ToString("N") + ".old";
- File.Move(shadowCopiedPlug.FullName, oldFile);
+ var oldFile = shadowCopiedPlug + Guid.NewGuid().ToString("N") + ".old";
+ _fileProvider.FileMove(shadowCopiedPlug, oldFile);
}
catch (IOException exc)
{
- throw new IOException(shadowCopiedPlug.FullName + " rename failed, cannot initialize plugin", exc);
+ throw new IOException(shadowCopiedPlug + " rename failed, cannot initialize plugin", exc);
}
//OK, we've made it this far, now retry the shadow copy
- File.Copy(plug.FullName, shadowCopiedPlug.FullName, true);
+ _fileProvider.FileCopy(pluginFilePath, shadowCopiedPlug, true);
}
return shadowCopiedPlug;
@@ -330,12 +337,20 @@ private static FileInfo ShadowCopyFile(FileInfo plug, DirectoryInfo shadowCopyPl
///
/// Determines if the folder is a bin plugin folder for a package
///
- ///
- ///
- private static bool IsPackagePluginFolder(DirectoryInfo folder)
+ /// Folder
+ /// True if the folder is a bin plugin folder for a package; otherwise false
+ private static bool IsPackagePluginFolder(string folder)
{
- if (folder?.Parent == null) return false;
- if (!folder.Parent.Name.Equals(PluginsPathName, StringComparison.InvariantCultureIgnoreCase)) return false;
+ if (string.IsNullOrEmpty(folder))
+ return false;
+
+ var parent = _fileProvider.GetParentDirectory(folder);
+
+ if (string.IsNullOrEmpty(parent))
+ return false;
+
+ if (!_fileProvider.GetDirectoryNameOnly(parent).Equals(PluginsPathName, StringComparison.InvariantCultureIgnoreCase))
+ return false;
return true;
}
@@ -361,54 +376,54 @@ public static void Initialize(ApplicationPartManager applicationPartManager, Nop
{
// TODO: Add verbose exception handling / raising here since this is happening on app startup and could
// prevent app from starting altogether
- var pluginFolder = new DirectoryInfo(CommonHelper.MapPath(PluginsPath));
- _shadowCopyFolder = new DirectoryInfo(CommonHelper.MapPath(ShadowCopyPath));
- _reserveShadowCopyFolder = new DirectoryInfo(Path.Combine(CommonHelper.MapPath(ShadowCopyPath), $"{RESERVE_SHADOW_COPY_FOLDER_NAME}{DateTime.Now.ToFileTimeUtc()}"));
-
+ var pluginFolder = _fileProvider.MapPath(PluginsPath);
+ _shadowCopyFolder = _fileProvider.MapPath(ShadowCopyPath);
+ _reserveShadowCopyFolder = _fileProvider.Combine(_fileProvider.MapPath(ShadowCopyPath), $"{RESERVE_SHADOW_COPY_FOLDER_NAME}{DateTime.Now.ToFileTimeUtc()}");
+
var referencedPlugins = new List();
var incompatiblePlugins = new List();
try
{
- var installedPluginSystemNames = GetInstalledPluginNames(CommonHelper.MapPath(InstalledPluginsFilePath));
+ var installedPluginSystemNames = GetInstalledPluginNames(_fileProvider.MapPath(InstalledPluginsFilePath));
Debug.WriteLine("Creating shadow copy folder and querying for DLLs");
//ensure folders are created
- Directory.CreateDirectory(pluginFolder.FullName);
- Directory.CreateDirectory(_shadowCopyFolder.FullName);
+ _fileProvider.CreateDirectory(pluginFolder);
+ _fileProvider.CreateDirectory(_shadowCopyFolder);
//get list of all files in bin
- var binFiles = _shadowCopyFolder.GetFiles("*", SearchOption.AllDirectories);
+ var binFiles = _fileProvider.GetFiles(_shadowCopyFolder, "*", false);
if (config.ClearPluginShadowDirectoryOnStartup)
{
//clear out shadow copied plugins
foreach (var f in binFiles)
{
- if(f.Name.Equals("placeholder.txt", StringComparison.InvariantCultureIgnoreCase))
+ if(_fileProvider.GetFileName(f).Equals("placeholder.txt", StringComparison.InvariantCultureIgnoreCase))
continue;
- Debug.WriteLine("Deleting " + f.Name);
+ Debug.WriteLine("Deleting " + f);
try
{
//ignore index.htm
- var fileName = Path.GetFileName(f.FullName);
+ var fileName = _fileProvider.GetFileName(f);
if (fileName.Equals("index.htm", StringComparison.InvariantCultureIgnoreCase))
continue;
- File.Delete(f.FullName);
+ _fileProvider.DeleteFile(f);
}
catch (Exception exc)
{
- Debug.WriteLine("Error deleting file " + f.Name + ". Exception: " + exc);
+ Debug.WriteLine("Error deleting file " + f + ". Exception: " + exc);
}
}
//delete all reserve folders
- foreach (var directory in _shadowCopyFolder.GetDirectories(RESERVE_SHADOW_COPY_FOLDER_NAME_PATTERN, SearchOption.TopDirectoryOnly))
+ foreach (var directory in _fileProvider.GetDirectories(_shadowCopyFolder, RESERVE_SHADOW_COPY_FOLDER_NAME_PATTERN))
{
try
{
- CommonHelper.DeleteDirectory(directory.FullName);
+ _fileProvider.DeleteDirectory(directory);
}
catch
{
@@ -432,7 +447,7 @@ public static void Initialize(ApplicationPartManager applicationPartManager, Nop
//some validation
if (string.IsNullOrWhiteSpace(pluginDescriptor.SystemName))
- throw new Exception($"A plugin '{descriptionFile.FullName}' has no system name. Try assigning the plugin a unique name and recompiling.");
+ throw new Exception($"A plugin '{descriptionFile}' has no system name. Try assigning the plugin a unique name and recompiling.");
if (referencedPlugins.Contains(pluginDescriptor))
throw new Exception($"A plugin with '{pluginDescriptor.SystemName}' system name is already defined");
@@ -442,19 +457,20 @@ public static void Initialize(ApplicationPartManager applicationPartManager, Nop
try
{
- if (descriptionFile.Directory == null)
- throw new Exception($"Directory cannot be resolved for '{descriptionFile.Name}' description file");
+ var directoryName = _fileProvider.GetDirectoryName(descriptionFile);
+ if (string.IsNullOrEmpty(directoryName))
+ throw new Exception($"Directory cannot be resolved for '{_fileProvider.GetFileName(descriptionFile)}' description file");
//get list of all DLLs in plugins (not in bin!)
- var pluginFiles = descriptionFile.Directory.GetFiles("*.dll", SearchOption.AllDirectories)
+ var pluginFiles = _fileProvider.GetFiles(directoryName, "*.dll", false)
//just make sure we're not registering shadow copied plugins
- .Where(x => !binFiles.Select(q => q.FullName).Contains(x.FullName))
- .Where(x => IsPackagePluginFolder(x.Directory))
+ .Where(x => !binFiles.Select(q => q).Contains(x))
+ .Where(x => IsPackagePluginFolder(_fileProvider.GetDirectoryName(x)))
.ToList();
//other plugin description info
var mainPluginFile = pluginFiles
- .FirstOrDefault(x => x.Name.Equals(pluginDescriptor.AssemblyFileName, StringComparison.InvariantCultureIgnoreCase));
+ .FirstOrDefault(x => _fileProvider.GetFileName(x).Equals(pluginDescriptor.AssemblyFileName, StringComparison.InvariantCultureIgnoreCase));
//plugin have wrong directory
if (mainPluginFile == null)
@@ -470,7 +486,7 @@ public static void Initialize(ApplicationPartManager applicationPartManager, Nop
//load all other referenced assemblies now
foreach (var plugin in pluginFiles
- .Where(x => !x.Name.Equals(mainPluginFile.Name, StringComparison.InvariantCultureIgnoreCase))
+ .Where(x => !_fileProvider.GetFileName(x).Equals(_fileProvider.GetFileName(mainPluginFile), StringComparison.InvariantCultureIgnoreCase))
.Where(x => !IsAlreadyLoaded(x)))
PerformFileDeploy(plugin, applicationPartManager, config);
@@ -530,14 +546,10 @@ public static void MarkPluginAsInstalled(string systemName)
if (string.IsNullOrEmpty(systemName))
throw new ArgumentNullException(nameof(systemName));
- var filePath = CommonHelper.MapPath(InstalledPluginsFilePath);
+ var filePath = _fileProvider.MapPath(InstalledPluginsFilePath);
//create file if not exists
- if (!File.Exists(filePath))
- {
- //we use 'using' to close the file after it's created
- using (File.Create(filePath)) { }
- }
+ _fileProvider.CreateFile(filePath);
//get installed plugin names
var installedPluginSystemNames = GetInstalledPluginNames(filePath);
@@ -560,14 +572,10 @@ public static void MarkPluginAsUninstalled(string systemName)
if (string.IsNullOrEmpty(systemName))
throw new ArgumentNullException(nameof(systemName));
- var filePath = CommonHelper.MapPath(InstalledPluginsFilePath);
+ var filePath = _fileProvider.MapPath(InstalledPluginsFilePath);
//create file if not exists
- if (!File.Exists(filePath))
- {
- //we use 'using' to close the file after it's created
- using (File.Create(filePath)) { }
- }
+ _fileProvider.CreateFile(filePath);
//get installed plugin names
var installedPluginSystemNames = GetInstalledPluginNames(filePath);
@@ -586,9 +594,9 @@ public static void MarkPluginAsUninstalled(string systemName)
///
public static void MarkAllPluginsAsUninstalled()
{
- var filePath = CommonHelper.MapPath(InstalledPluginsFilePath);
- if (File.Exists(filePath))
- File.Delete(filePath);
+ var filePath = _fileProvider.MapPath(InstalledPluginsFilePath);
+ if (_fileProvider.FileExists(filePath))
+ _fileProvider.DeleteFile(filePath);
}
///
@@ -601,11 +609,9 @@ public static PluginDescriptor FindPlugin(Type typeInAssembly)
if (typeInAssembly == null)
throw new ArgumentNullException(nameof(typeInAssembly));
- if (ReferencedPlugins == null)
- return null;
-
- return ReferencedPlugins.FirstOrDefault(plugin => plugin.ReferencedAssembly != null
- && plugin.ReferencedAssembly.FullName.Equals(typeInAssembly.Assembly.FullName, StringComparison.InvariantCultureIgnoreCase));
+ return ReferencedPlugins?.FirstOrDefault(plugin =>
+ plugin.ReferencedAssembly != null &&
+ plugin.ReferencedAssembly.FullName.Equals(typeInAssembly.Assembly.FullName, StringComparison.InvariantCultureIgnoreCase));
}
///
@@ -615,7 +621,7 @@ public static PluginDescriptor FindPlugin(Type typeInAssembly)
/// Plugin descriptor
public static PluginDescriptor GetPluginDescriptorFromFile(string filePath)
{
- var text = File.ReadAllText(filePath);
+ var text = _fileProvider.ReadAllText(filePath, Encoding.UTF8);
return GetPluginDescriptorFromText(text);
}
@@ -653,13 +659,13 @@ public static void SavePluginDescriptor(PluginDescriptor pluginDescriptor)
if (pluginDescriptor.OriginalAssemblyFile == null)
throw new Exception($"Cannot load original assembly path for {pluginDescriptor.SystemName} plugin.");
- var filePath = Path.Combine(pluginDescriptor.OriginalAssemblyFile.Directory.FullName, PluginDescriptionFileName);
- if (!File.Exists(filePath))
+ var filePath = _fileProvider.Combine(_fileProvider.GetDirectoryName(pluginDescriptor.OriginalAssemblyFile), PluginDescriptionFileName);
+ if (!_fileProvider.FileExists(filePath))
throw new Exception($"Description file for {pluginDescriptor.SystemName} plugin does not exist. {filePath}");
//save the file
var text = JsonConvert.SerializeObject(pluginDescriptor, Formatting.Indented);
- File.WriteAllText(filePath, text);
+ _fileProvider.WriteAllText(filePath, text, Encoding.UTF8);
}
///
@@ -677,8 +683,10 @@ public static bool DeletePlugin(PluginDescriptor pluginDescriptor)
if (pluginDescriptor.Installed)
return false;
- if (pluginDescriptor.OriginalAssemblyFile.Directory.Exists)
- CommonHelper.DeleteDirectory(pluginDescriptor.OriginalAssemblyFile.DirectoryName);
+ var directoryName = _fileProvider.GetDirectoryName(pluginDescriptor.OriginalAssemblyFile);
+
+ if ( _fileProvider.DirectoryExists(directoryName))
+ _fileProvider.DeleteDirectory(directoryName);
return true;
}
diff --git a/src/Libraries/Nop.Core/WebHelper.cs b/src/Libraries/Nop.Core/WebHelper.cs
index 0efa8fd270a..2e7aa79c2a1 100644
--- a/src/Libraries/Nop.Core/WebHelper.cs
+++ b/src/Libraries/Nop.Core/WebHelper.cs
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
-using System.IO;
using System.Linq;
using System.Net;
using System.Text;
@@ -30,6 +29,7 @@ public partial class WebHelper : IWebHelper
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly HostingConfig _hostingConfig;
+ private readonly INopFileProvider _fileProvider;
#endregion
@@ -40,10 +40,13 @@ public partial class WebHelper : IWebHelper
///
/// Hosting config
/// HTTP context accessor
- public WebHelper(HostingConfig hostingConfig, IHttpContextAccessor httpContextAccessor)
+ /// File provider
+ public WebHelper(HostingConfig hostingConfig, IHttpContextAccessor httpContextAccessor,
+ INopFileProvider fileProvider)
{
this._hostingConfig = hostingConfig;
this._httpContextAccessor = httpContextAccessor;
+ this._fileProvider = fileProvider;
}
#endregion
@@ -90,7 +93,7 @@ protected virtual bool TryWriteWebConfig()
{
try
{
- File.SetLastWriteTimeUtc(CommonHelper.MapPath("~/web.config"), DateTime.UtcNow);
+ _fileProvider.SetLastWriteTimeUtc(_fileProvider.MapPath("~/web.config"), DateTime.UtcNow);
return true;
}
catch
diff --git a/src/Libraries/Nop.Data/Initializers/SqlCeInitializer.cs b/src/Libraries/Nop.Data/Initializers/SqlCeInitializer.cs
index 0d880afdb26..678a6bb7904 100644
--- a/src/Libraries/Nop.Data/Initializers/SqlCeInitializer.cs
+++ b/src/Libraries/Nop.Data/Initializers/SqlCeInitializer.cs
@@ -1,7 +1,7 @@
using System;
using System.Data.Entity;
using System.Data.SqlServerCe;
-using System.IO;
+using Nop.Core.Infrastructure;
namespace Nop.Data.Initializers
{
@@ -57,11 +57,12 @@ private static string ReplaceDataDirectory(string inputString)
data = string.Empty;
}
var length = "|DataDirectory|".Length;
- if ((inputString.Length > "|DataDirectory|".Length) && ('\\' == inputString["|DataDirectory|".Length]))
+ if (inputString.Length > "|DataDirectory|".Length && ('\\' == inputString["|DataDirectory|".Length]))
{
length++;
}
- return Path.Combine(data, inputString.Substring(length));
+ var fileProvider = EngineContext.Current.Resolve();
+ return fileProvider.Combine(data, inputString.Substring(length));
}
#endregion
diff --git a/src/Libraries/Nop.Data/SqlServerDataProvider.cs b/src/Libraries/Nop.Data/SqlServerDataProvider.cs
index d6e262544cc..c995bbfffa3 100644
--- a/src/Libraries/Nop.Data/SqlServerDataProvider.cs
+++ b/src/Libraries/Nop.Data/SqlServerDataProvider.cs
@@ -6,8 +6,8 @@
using System.Data.SqlClient;
using System.IO;
using System.Text;
-using Nop.Core;
using Nop.Core.Data;
+using Nop.Core.Infrastructure;
using Nop.Data.Initializers;
namespace Nop.Data
@@ -27,7 +27,9 @@ public class SqlServerDataProvider : IDataProvider
///
protected virtual string[] ParseCommands(string filePath, bool throwExceptionIfNonExists)
{
- if (!File.Exists(filePath))
+ var fileProvider = EngineContext.Current.Resolve();
+
+ if (!fileProvider.FileExists(filePath))
{
if (throwExceptionIfNonExists)
throw new ArgumentException($"Specified file doesn't exist - {filePath}");
@@ -36,8 +38,7 @@ protected virtual string[] ParseCommands(string filePath, bool throwExceptionIfN
}
var statements = new List();
- using (var stream = File.OpenRead(filePath))
- using (var reader = new StreamReader(stream))
+ using (var reader = new StreamReader(filePath))
{
string statement;
while ((statement = ReadNextStatementFromStream(reader)) != null)
@@ -112,9 +113,11 @@ public virtual void SetDatabaseInitializer()
//custom commands (stored procedures, indexes)
+ var fileProvider = EngineContext.Current.Resolve();
+
var customCommands = new List();
- customCommands.AddRange(ParseCommands(CommonHelper.MapPath("~/App_Data/Install/SqlServer.Indexes.sql"), false));
- customCommands.AddRange(ParseCommands(CommonHelper.MapPath("~/App_Data/Install/SqlServer.StoredProcedures.sql"), false));
+ customCommands.AddRange(ParseCommands(fileProvider.MapPath("~/App_Data/Install/SqlServer.Indexes.sql"), false));
+ customCommands.AddRange(ParseCommands(fileProvider.MapPath("~/App_Data/Install/SqlServer.StoredProcedures.sql"), false));
var initializer = new CreateTablesIfNotExist(tablesToValidate, customCommands.ToArray());
Database.SetInitializer(initializer);
diff --git a/src/Libraries/Nop.Services/Common/IMaintenanceService.cs b/src/Libraries/Nop.Services/Common/IMaintenanceService.cs
index 8cbc93076f6..c2ed20e5edf 100644
--- a/src/Libraries/Nop.Services/Common/IMaintenanceService.cs
+++ b/src/Libraries/Nop.Services/Common/IMaintenanceService.cs
@@ -1,5 +1,4 @@
using System.Collections.Generic;
-using System.IO;
using Nop.Core;
namespace Nop.Services.Common
@@ -27,7 +26,7 @@ public partial interface IMaintenanceService
/// Gets all backup files
///
/// Backup file collection
- IList GetAllBackupFiles();
+ IList GetAllBackupFiles();
///
/// Creates a backup of the database
diff --git a/src/Libraries/Nop.Services/Common/MaintenanceService.cs b/src/Libraries/Nop.Services/Common/MaintenanceService.cs
index 7127ffc5dab..2cfa4e7bfa7 100644
--- a/src/Libraries/Nop.Services/Common/MaintenanceService.cs
+++ b/src/Libraries/Nop.Services/Common/MaintenanceService.cs
@@ -5,10 +5,10 @@
using System.Data.SqlClient;
using System.IO;
using System.Linq;
-using Microsoft.AspNetCore.Hosting;
using Nop.Core;
using Nop.Core.Data;
using Nop.Core.Domain.Common;
+using Nop.Core.Infrastructure;
using Nop.Data;
namespace Nop.Services.Common
@@ -23,7 +23,7 @@ public partial class MaintenanceService : IMaintenanceService
private readonly IDataProvider _dataProvider;
private readonly IDbContext _dbContext;
private readonly CommonSettings _commonSettings;
- private readonly IHostingEnvironment _hostingEnvironment;
+ private readonly INopFileProvider _fileProvider;
#endregion
@@ -35,14 +35,14 @@ public partial class MaintenanceService : IMaintenanceService
/// Data provider
/// Database Context
/// Common settings
- /// Hosting environment
+ /// File provider
public MaintenanceService(IDataProvider dataProvider, IDbContext dbContext,
- CommonSettings commonSettings, IHostingEnvironment hostingEnvironment)
+ CommonSettings commonSettings, INopFileProvider fileProvider)
{
this._dataProvider = dataProvider;
this._dbContext = dbContext;
this._commonSettings = commonSettings;
- this._hostingEnvironment = hostingEnvironment;
+ this._fileProvider = fileProvider;
}
#endregion
@@ -56,9 +56,9 @@ public MaintenanceService(IDataProvider dataProvider, IDbContext dbContext,
///
protected virtual string GetBackupDirectoryPath(bool ensureFolderCreated = true)
{
- var path = Path.Combine(_hostingEnvironment.WebRootPath, "db_backups\\");
+ var path = _fileProvider.GetAbsolutePath("db_backups\\");
if (ensureFolderCreated)
- System.IO.Directory.CreateDirectory(path);
+ _fileProvider.CreateDirectory(path);
return path;
}
@@ -83,16 +83,14 @@ protected virtual void CheckBackupSupported()
/// Integer ident; null if cannot get the result
public virtual int? GetTableIdent() where T: BaseEntity
{
- if (_commonSettings.UseStoredProceduresIfSupported && _dataProvider.StoredProceduredSupported)
- {
- //stored procedures are enabled and supported by the database
- var tableName = _dbContext.GetTableName();
- var result = _dbContext.SqlQuery($"SELECT IDENT_CURRENT('[{tableName}]')").FirstOrDefault();
- return result.HasValue ? Convert.ToInt32(result) : 1;
- }
-
//stored procedures aren't supported
- return null;
+ if (!_commonSettings.UseStoredProceduresIfSupported || !_dataProvider.StoredProceduredSupported)
+ return null;
+
+ //stored procedures are enabled and supported by the database
+ var tableName = _dbContext.GetTableName();
+ var result = _dbContext.SqlQuery($"SELECT IDENT_CURRENT('[{tableName}]')").FirstOrDefault();
+ return result.HasValue ? Convert.ToInt32(result) : 1;
}
///
@@ -104,14 +102,13 @@ public virtual void SetTableIdent(int ident) where T : BaseEntity
{
if (_commonSettings.UseStoredProceduresIfSupported && _dataProvider.StoredProceduredSupported)
{
- //stored procedures are enabled and supported by the database.
-
var currentIdent = GetTableIdent();
- if (currentIdent.HasValue && ident > currentIdent.Value)
- {
- var tableName = _dbContext.GetTableName();
- _dbContext.ExecuteSqlCommand($"DBCC CHECKIDENT([{tableName}], RESEED, {ident})");
- }
+ if (!currentIdent.HasValue || ident <= currentIdent.Value)
+ return;
+
+ //stored procedures are enabled and supported by the database.
+ var tableName = _dbContext.GetTableName();
+ _dbContext.ExecuteSqlCommand($"DBCC CHECKIDENT([{tableName}], RESEED, {ident})");
}
else
{
@@ -123,16 +120,17 @@ public virtual void SetTableIdent(int ident) where T : BaseEntity
/// Gets all backup files
///
/// Backup file collection
- public virtual IList GetAllBackupFiles()
+ public virtual IList GetAllBackupFiles()
{
var path = GetBackupDirectoryPath();
- if (!System.IO.Directory.Exists(path))
+ if (!_fileProvider.DirectoryExists(path))
{
throw new IOException("Backup directory not exists");
}
-
- return System.IO.Directory.GetFiles(path, "*.bak").Select(fullPath => new FileInfo(fullPath)).OrderByDescending(p => p.CreationTime).ToList();
+
+ return _fileProvider.GetFiles(path, "*.bak")
+ .OrderByDescending(p => _fileProvider.GetLastWriteTime(p)).ToList();
}
///
@@ -141,17 +139,9 @@ public virtual IList GetAllBackupFiles()
public virtual void BackupDatabase()
{
CheckBackupSupported();
- var fileName = string.Format(
- "{0}database_{1}_{2}.bak",
- GetBackupDirectoryPath(),
- DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"),
- CommonHelper.GenerateRandomDigitCode(10));
-
- var commandText = string.Format(
- "BACKUP DATABASE [{0}] TO DISK = '{1}' WITH FORMAT",
- _dbContext.DbName(),
- fileName);
+ var fileName = $"{GetBackupDirectoryPath()}database_{DateTime.Now:yyyy-MM-dd-HH-mm-ss}_{CommonHelper.GenerateRandomDigitCode(10)}.bak";
+ var commandText = $"BACKUP DATABASE [{_dbContext.DbName()}] TO DISK = '{fileName}' WITH FORMAT";
_dbContext.ExecuteSqlCommand(commandText, true);
}
@@ -163,7 +153,7 @@ public virtual void BackupDatabase()
public virtual void RestoreDatabase(string backupFileName)
{
CheckBackupSupported();
- var settings = new DataSettingsManager();
+ var settings = new DataSettingsManager(_fileProvider);
var conn = new SqlConnectionStringBuilder(settings.LoadSettings().DataConnectionString)
{
InitialCatalog = "master"
@@ -206,7 +196,7 @@ public virtual void RestoreDatabase(string backupFileName)
/// The path to the backup file
public virtual string GetBackupPath(string backupFileName)
{
- return Path.Combine(GetBackupDirectoryPath(), backupFileName);
+ return _fileProvider.Combine(GetBackupDirectoryPath(), backupFileName);
}
#endregion
diff --git a/src/Libraries/Nop.Services/Common/PdfService.cs b/src/Libraries/Nop.Services/Common/PdfService.cs
index 55c6c772338..1b988c8730b 100644
--- a/src/Libraries/Nop.Services/Common/PdfService.cs
+++ b/src/Libraries/Nop.Services/Common/PdfService.cs
@@ -17,6 +17,7 @@
using Nop.Core.Domain.Tax;
using Nop.Core.Domain.Vendors;
using Nop.Core.Html;
+using Nop.Core.Infrastructure;
using Nop.Services.Catalog;
using Nop.Services.Configuration;
using Nop.Services.Directory;
@@ -61,6 +62,7 @@ public partial class PdfService : IPdfService
private readonly AddressSettings _addressSettings;
private readonly IVendorService _vendorService;
private readonly VendorSettings _vendorSettings;
+ private readonly INopFileProvider _fileProvider;
#endregion
@@ -93,6 +95,7 @@ public partial class PdfService : IPdfService
/// Address settings
/// Vendor service
/// Vendor settings
+ /// File provider
public PdfService(ILocalizationService localizationService,
ILanguageService languageService,
IWorkContext workContext,
@@ -116,7 +119,8 @@ public PdfService(ILocalizationService localizationService,
TaxSettings taxSettings,
AddressSettings addressSettings,
IVendorService vendorService,
- VendorSettings vendorSettings)
+ VendorSettings vendorSettings,
+ INopFileProvider fileProvider)
{
this._localizationService = localizationService;
this._languageService = languageService;
@@ -142,6 +146,7 @@ public PdfService(ILocalizationService localizationService,
this._addressSettings = addressSettings;
this._vendorService = vendorService;
this._vendorSettings = vendorSettings;
+ this._fileProvider = fileProvider;
}
#endregion
@@ -169,7 +174,7 @@ protected virtual Font GetFont(string fontFileName)
if (fontFileName == null)
throw new ArgumentNullException(nameof(fontFileName));
- var fontPath = Path.Combine(CommonHelper.MapPath("~/App_Data/Pdf/"), fontFileName);
+ var fontPath = _fileProvider.Combine(_fileProvider.MapPath("~/App_Data/Pdf/"), fontFileName);
var baseFont = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
var font = new Font(baseFont, 10, Font.NORMAL);
return font;
@@ -1178,7 +1183,7 @@ public virtual string PrintOrderToPdf(Order order, int languageId = 0, int vendo
throw new ArgumentNullException(nameof(order));
var fileName = $"order_{order.OrderGuid}_{CommonHelper.GenerateRandomDigitCode(4)}.pdf";
- var filePath = Path.Combine(CommonHelper.MapPath("~/wwwroot/files/exportimport"), fileName);
+ var filePath = _fileProvider.Combine(_fileProvider.MapPath("~/wwwroot/files/exportimport"), fileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
var orders = new List {order};
diff --git a/src/Libraries/Nop.Services/Directory/GeoLookupService.cs b/src/Libraries/Nop.Services/Directory/GeoLookupService.cs
index 3e4bdac822b..800e3ffac05 100644
--- a/src/Libraries/Nop.Services/Directory/GeoLookupService.cs
+++ b/src/Libraries/Nop.Services/Directory/GeoLookupService.cs
@@ -4,7 +4,7 @@
using MaxMind.GeoIP2;
using MaxMind.GeoIP2.Exceptions;
using MaxMind.GeoIP2.Responses;
-using Nop.Core;
+using Nop.Core.Infrastructure;
using Nop.Services.Logging;
namespace Nop.Services.Directory
@@ -17,6 +17,7 @@ public partial class GeoLookupService : IGeoLookupService
#region Fields
private readonly ILogger _logger;
+ private readonly INopFileProvider _fileProvider;
#endregion
@@ -26,9 +27,11 @@ public partial class GeoLookupService : IGeoLookupService
/// Ctor
///
/// Logger
- public GeoLookupService(ILogger logger)
+ /// File provider
+ public GeoLookupService(ILogger logger, INopFileProvider fileProvider)
{
this._logger = logger;
+ this._fileProvider = fileProvider;
}
#endregion
@@ -48,7 +51,7 @@ protected virtual CountryResponse GetInformation(string ipAddress)
try
{
//This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com
- var databasePath = CommonHelper.MapPath("~/App_Data/GeoLite2-Country.mmdb");
+ var databasePath = _fileProvider.MapPath("~/App_Data/GeoLite2-Country.mmdb");
var reader = new DatabaseReader(databasePath);
var omni = reader.Country(ipAddress);
return omni;
diff --git a/src/Libraries/Nop.Services/ExportImport/ImportManager.cs b/src/Libraries/Nop.Services/ExportImport/ImportManager.cs
index 0babaf163d7..a5cd8eaa8bf 100644
--- a/src/Libraries/Nop.Services/ExportImport/ImportManager.cs
+++ b/src/Libraries/Nop.Services/ExportImport/ImportManager.cs
@@ -29,6 +29,7 @@
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Nop.Services.Stores;
+using Nop.Core.Infrastructure;
namespace Nop.Services.ExportImport
{
@@ -77,6 +78,7 @@ public partial class ImportManager : IImportManager
private readonly ISpecificationAttributeService _specificationAttributeService;
private readonly ILogger _logger;
private readonly IStoreMappingService _storeMappingService;
+ private readonly INopFileProvider _fileProvider;
#endregion
@@ -110,7 +112,8 @@ public ImportManager(IProductService productService,
ISpecificationAttributeService specificationAttributeService,
ILogger logger,
IServiceScopeFactory serviceScopeFactory,
- IStoreMappingService storeMappingService)
+ IStoreMappingService storeMappingService,
+ INopFileProvider fileProvider)
{
this._productService = productService;
this._categoryService = categoryService;
@@ -141,6 +144,7 @@ public ImportManager(IProductService productService,
this._logger = logger;
this._serviceScopeFactory = serviceScopeFactory;
this._storeMappingService = storeMappingService;
+ this._fileProvider = fileProvider;
}
#endregion
@@ -223,11 +227,11 @@ protected virtual string GetMimeTypeFromFilePath(string filePath)
/// The image or null if the image has not changed
protected virtual Picture LoadPicture(string picturePath, string name, int? picId = null)
{
- if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))
+ if (string.IsNullOrEmpty(picturePath) || !_fileProvider.FileExists(picturePath))
return null;
var mimeType = GetMimeTypeFromFilePath(picturePath);
- var newPictureBinary = File.ReadAllBytes(picturePath);
+ var newPictureBinary = _fileProvider.ReadAllBytes(picturePath);
var pictureAlreadyExists = false;
if (picId != null)
{
@@ -254,9 +258,11 @@ protected virtual Picture LoadPicture(string picturePath, string name, int? picI
private void LogPictureInsertError(string picturePath, Exception ex)
{
- var fi = new FileInfo(picturePath);
- var point = string.IsNullOrEmpty(fi.Extension) ? string.Empty : ".";
- var fileName = fi.Exists ? $"{fi.Name}{point}{fi.Extension}" : string.Empty;
+ var extension = _fileProvider.GetFileExtension(picturePath);
+ var name = _fileProvider.GetFileNameWithoutExtension(picturePath);
+
+ var point = string.IsNullOrEmpty(extension) ? string.Empty : ".";
+ var fileName = _fileProvider.FileExists(picturePath) ? $"{name}{point}{extension}" : string.Empty;
_logger.Error($"Insert picture failed (file name: {fileName})", ex);
}
@@ -270,7 +276,7 @@ protected virtual void ImportProductImagesUsingServices(IList downloadedFiles)
return string.Empty;
//ensure that temp directory is created
- var tempDirectory = CommonHelper.MapPath(UPLOADS_TEMP_PATH);
- System.IO.Directory.CreateDirectory(new DirectoryInfo(tempDirectory).FullName);
+ var tempDirectory = _fileProvider.MapPath(UPLOADS_TEMP_PATH);
+ _fileProvider.CreateDirectory(tempDirectory);
- var fileName = Path.GetFileName(urlString);
+ var fileName = _fileProvider.GetFileName(urlString);
if (string.IsNullOrEmpty(fileName))
return string.Empty;
- var filePath = Path.Combine(tempDirectory, fileName);
+ var filePath = _fileProvider.Combine(tempDirectory, fileName);
try
{
WebRequest.Create(urlString);
@@ -1044,7 +1050,7 @@ private void ImportProductsFromSplitedXlsx(ExcelWorksheet worksheet, ImportProdu
try
{
- File.Delete(path);
+ _fileProvider.DeleteFile(path);
}
catch
{
@@ -1071,7 +1077,7 @@ private IList SplitProductFile(ExcelWorksheet worksheet, ImportProductMe
? metadata.ProductsInFile[curIndex - 1]
: metadata.EndRow;
- var filePath = $"{CommonHelper.MapPath(UPLOADS_TEMP_PATH)}/{fileName}_part_{fileIndex}.xlsx";
+ var filePath = $"{_fileProvider.MapPath(UPLOADS_TEMP_PATH)}/{fileName}_part_{fileIndex}.xlsx";
CopyDataToNewFile(metadata, worksheet, filePath, startRow, endRow, endCell);
@@ -1702,12 +1708,12 @@ public virtual void ImportProductsFromXlsx(Stream stream)
foreach (var downloadedFile in downloadedFiles)
{
- if(!File.Exists(downloadedFile))
+ if(!_fileProvider.FileExists(downloadedFile))
continue;
try
{
- File.Delete(downloadedFile);
+ _fileProvider.DeleteFile(downloadedFile);
}
catch
{
diff --git a/src/Libraries/Nop.Services/Helpers/BrowscapXmlParser.cs b/src/Libraries/Nop.Services/Helpers/BrowscapXmlParser.cs
index ee5eb99725e..a643623ff4d 100644
--- a/src/Libraries/Nop.Services/Helpers/BrowscapXmlParser.cs
+++ b/src/Libraries/Nop.Services/Helpers/BrowscapXmlParser.cs
@@ -5,6 +5,7 @@
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
+using Nop.Core.Infrastructure;
namespace Nop.Services.Helpers
{
@@ -14,15 +15,18 @@ namespace Nop.Services.Helpers
public class BrowscapXmlHelper
{
private readonly List _crawlerUserAgentsRegexp;
+ private readonly INopFileProvider _fileProvider;
///
/// Ctor
///
/// User agent file path
/// User agent with crawlers only file path
- public BrowscapXmlHelper(string userAgentStringsPath, string crawlerOnlyUserAgentStringsPath)
+ /// File provider
+ public BrowscapXmlHelper(string userAgentStringsPath, string crawlerOnlyUserAgentStringsPath, INopFileProvider fileProvider)
{
- _crawlerUserAgentsRegexp = new List();
+ this._crawlerUserAgentsRegexp = new List();
+ this._fileProvider = fileProvider;
Initialize(userAgentStringsPath, crawlerOnlyUserAgentStringsPath);
}
@@ -32,7 +36,7 @@ private void Initialize(string userAgentStringsPath, string crawlerOnlyUserAgent
List crawlerItems = null;
var needSaveCrawlerOnly = false;
- if (!string.IsNullOrEmpty(crawlerOnlyUserAgentStringsPath) && File.Exists(crawlerOnlyUserAgentStringsPath))
+ if (!string.IsNullOrEmpty(crawlerOnlyUserAgentStringsPath) && _fileProvider.FileExists(crawlerOnlyUserAgentStringsPath))
{
//try to load crawler list from crawlers only file
using (var sr = new StreamReader(crawlerOnlyUserAgentStringsPath))
@@ -63,7 +67,7 @@ private void Initialize(string userAgentStringsPath, string crawlerOnlyUserAgent
.Select(e => e.Value)
.Select(ToRegexp));
- if ((string.IsNullOrEmpty(crawlerOnlyUserAgentStringsPath) || File.Exists(crawlerOnlyUserAgentStringsPath)) && !needSaveCrawlerOnly)
+ if ((string.IsNullOrEmpty(crawlerOnlyUserAgentStringsPath) || _fileProvider.FileExists(crawlerOnlyUserAgentStringsPath)) && !needSaveCrawlerOnly)
return;
//try to write crawlers file
diff --git a/src/Libraries/Nop.Services/Helpers/UserAgentHelper.cs b/src/Libraries/Nop.Services/Helpers/UserAgentHelper.cs
index e371ec0087a..bb99beb9fd8 100644
--- a/src/Libraries/Nop.Services/Helpers/UserAgentHelper.cs
+++ b/src/Libraries/Nop.Services/Helpers/UserAgentHelper.cs
@@ -3,7 +3,6 @@
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
-using Nop.Core;
using Nop.Core.Configuration;
using Nop.Core.Infrastructure;
@@ -18,6 +17,7 @@ public partial class UserAgentHelper : IUserAgentHelper
private readonly NopConfig _nopConfig;
private readonly IHttpContextAccessor _httpContextAccessor;
+ private readonly INopFileProvider _fileProvider;
private static readonly object _locker = new object();
#endregion
@@ -29,10 +29,12 @@ public partial class UserAgentHelper : IUserAgentHelper
///
/// Config
/// HTTP context accessor
- public UserAgentHelper(NopConfig nopConfig, IHttpContextAccessor httpContextAccessor)
+ /// File provider
+ public UserAgentHelper(NopConfig nopConfig, IHttpContextAccessor httpContextAccessor, INopFileProvider fileProvider)
{
this._nopConfig = nopConfig;
this._httpContextAccessor = httpContextAccessor;
+ this._fileProvider = fileProvider;
}
#endregion
@@ -60,12 +62,12 @@ protected virtual BrowscapXmlHelper GetBrowscapXmlHelper()
if (Singleton.Instance != null)
return Singleton.Instance;
- var userAgentStringsPath = CommonHelper.MapPath(_nopConfig.UserAgentStringsPath);
+ var userAgentStringsPath = _fileProvider.MapPath(_nopConfig.UserAgentStringsPath);
var crawlerOnlyUserAgentStringsPath = !string.IsNullOrEmpty(_nopConfig.CrawlerOnlyUserAgentStringsPath)
- ? CommonHelper.MapPath(_nopConfig.CrawlerOnlyUserAgentStringsPath)
+ ? _fileProvider.MapPath(_nopConfig.CrawlerOnlyUserAgentStringsPath)
: string.Empty;
- var browscapXmlHelper = new BrowscapXmlHelper(userAgentStringsPath, crawlerOnlyUserAgentStringsPath);
+ var browscapXmlHelper = new BrowscapXmlHelper(userAgentStringsPath, crawlerOnlyUserAgentStringsPath, _fileProvider);
Singleton.Instance = browscapXmlHelper;
return Singleton.Instance;
diff --git a/src/Libraries/Nop.Services/Installation/CodeFirstInstallationService.cs b/src/Libraries/Nop.Services/Installation/CodeFirstInstallationService.cs
index 9588fd199ae..3602e7774a6 100644
--- a/src/Libraries/Nop.Services/Installation/CodeFirstInstallationService.cs
+++ b/src/Libraries/Nop.Services/Installation/CodeFirstInstallationService.cs
@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
-using System.IO;
using System.Linq;
+using System.Text;
using Microsoft.AspNetCore.Hosting;
using Nop.Core;
using Nop.Core.Data;
@@ -105,6 +105,7 @@ public partial class CodeFirstInstallationService : IInstallationService
private readonly IGenericAttributeService _genericAttributeService;
private readonly IWebHelper _webHelper;
private readonly IHostingEnvironment _hostingEnvironment;
+ private readonly INopFileProvider _fileProvider;
#endregion
@@ -165,7 +166,8 @@ public CodeFirstInstallationService(IRepository storeRepository,
IRepository stockQuantityHistoryRepository,
IGenericAttributeService genericAttributeService,
IWebHelper webHelper,
- IHostingEnvironment hostingEnvironment)
+ IHostingEnvironment hostingEnvironment,
+ INopFileProvider fileProvider)
{
this._storeRepository = storeRepository;
this._measureDimensionRepository = measureDimensionRepository;
@@ -223,6 +225,7 @@ public CodeFirstInstallationService(IRepository storeRepository,
this._genericAttributeService = genericAttributeService;
this._webHelper = webHelper;
this._hostingEnvironment = hostingEnvironment;
+ this._fileProvider = fileProvider;
}
#endregion
@@ -231,7 +234,7 @@ public CodeFirstInstallationService(IRepository storeRepository,
protected virtual string GetSamplesPath()
{
- return Path.Combine(_hostingEnvironment.WebRootPath, "images\\samples\\");
+ return _fileProvider.GetAbsolutePath("images\\samples\\");
}
protected virtual void InstallStores()
@@ -383,9 +386,9 @@ protected virtual void InstallLocaleResources()
var language = _languageRepository.Table.Single(l => l.Name == "English");
//save resources
- foreach (var filePath in System.IO.Directory.EnumerateFiles(CommonHelper.MapPath("~/App_Data/Localization/"), "*.nopres.xml", SearchOption.TopDirectoryOnly))
+ foreach (var filePath in _fileProvider.EnumerateFiles(_fileProvider.MapPath("~/App_Data/Localization/"), "*.nopres.xml"))
{
- var localesXml = File.ReadAllText(filePath);
+ var localesXml = _fileProvider.ReadAllText(filePath, Encoding.UTF8);
var localizationService = EngineContext.Current.Resolve();
localizationService.ImportResourcesFromXml(language, localesXml);
}
@@ -6745,7 +6748,7 @@ protected virtual void InstallCategories()
PageSize = 6,
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_computers.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Computers")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_computers.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Computers")).Id,
IncludeInTopMenu = true,
Published = true,
DisplayOrder = 1,
@@ -6763,7 +6766,7 @@ protected virtual void InstallCategories()
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
ParentCategoryId = categoryComputers.Id,
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_desktops.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Desktops")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_desktops.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Desktops")).Id,
PriceRanges = "-1000;1000-1200;1200-;",
IncludeInTopMenu = true,
Published = true,
@@ -6782,7 +6785,7 @@ protected virtual void InstallCategories()
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
ParentCategoryId = categoryComputers.Id,
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_notebooks.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Notebooks")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_notebooks.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Notebooks")).Id,
IncludeInTopMenu = true,
Published = true,
DisplayOrder = 2,
@@ -6800,7 +6803,7 @@ protected virtual void InstallCategories()
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
ParentCategoryId = categoryComputers.Id,
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_software.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Software")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_software.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Software")).Id,
IncludeInTopMenu = true,
Published = true,
DisplayOrder = 3,
@@ -6817,7 +6820,7 @@ protected virtual void InstallCategories()
PageSize = 6,
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_electronics.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Electronics")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_electronics.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Electronics")).Id,
IncludeInTopMenu = true,
Published = true,
ShowOnHomePage = true,
@@ -6836,7 +6839,7 @@ protected virtual void InstallCategories()
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
ParentCategoryId = categoryElectronics.Id,
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_camera_photo.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Camera, photo")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_camera_photo.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Camera, photo")).Id,
PriceRanges = "-500;500-;",
IncludeInTopMenu = true,
Published = true,
@@ -6855,7 +6858,7 @@ protected virtual void InstallCategories()
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
ParentCategoryId = categoryElectronics.Id,
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_cell_phones.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Cell phones")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_cell_phones.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Cell phones")).Id,
IncludeInTopMenu = true,
Published = true,
DisplayOrder = 2,
@@ -6873,7 +6876,7 @@ protected virtual void InstallCategories()
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
ParentCategoryId = categoryElectronics.Id,
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_accessories.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Accessories")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_accessories.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Accessories")).Id,
IncludeInTopMenu = true,
PriceRanges = "-100;100-;",
Published = true,
@@ -6891,7 +6894,7 @@ protected virtual void InstallCategories()
PageSize = 6,
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_apparel.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Apparel")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_apparel.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Apparel")).Id,
IncludeInTopMenu = true,
Published = true,
ShowOnHomePage = true,
@@ -6910,7 +6913,7 @@ protected virtual void InstallCategories()
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
ParentCategoryId = categoryApparel.Id,
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_shoes.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Shoes")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_shoes.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Shoes")).Id,
PriceRanges = "-500;500-;",
IncludeInTopMenu = true,
Published = true,
@@ -6929,7 +6932,7 @@ protected virtual void InstallCategories()
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
ParentCategoryId = categoryApparel.Id,
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_clothing.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Clothing")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_clothing.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Clothing")).Id,
IncludeInTopMenu = true,
Published = true,
DisplayOrder = 2,
@@ -6947,7 +6950,7 @@ protected virtual void InstallCategories()
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
ParentCategoryId = categoryApparel.Id,
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_apparel_accessories.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Apparel Accessories")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_apparel_accessories.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Apparel Accessories")).Id,
IncludeInTopMenu = true,
PriceRanges = "-100;100-;",
Published = true,
@@ -6965,7 +6968,7 @@ protected virtual void InstallCategories()
PageSize = 6,
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_digital_downloads.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Digital downloads")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_digital_downloads.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Digital downloads")).Id,
IncludeInTopMenu = true,
Published = true,
ShowOnHomePage = true,
@@ -6985,7 +6988,7 @@ protected virtual void InstallCategories()
PageSize = 6,
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_book.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Book")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_book.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Book")).Id,
PriceRanges = "-25;25-50;50-;",
IncludeInTopMenu = true,
Published = true,
@@ -7003,7 +7006,7 @@ protected virtual void InstallCategories()
PageSize = 6,
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_jewelry.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Jewelry")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_jewelry.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Jewelry")).Id,
PriceRanges = "0-500;500-700;700-3000;",
IncludeInTopMenu = true,
Published = true,
@@ -7021,7 +7024,7 @@ protected virtual void InstallCategories()
PageSize = 6,
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "category_gift_cards.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Gift Cards")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "category_gift_cards.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Gift Cards")).Id,
IncludeInTopMenu = true,
Published = true,
DisplayOrder = 7,
@@ -7064,7 +7067,7 @@ protected virtual void InstallManufacturers()
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
Published = true,
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "manufacturer_apple.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Apple")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "manufacturer_apple.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Apple")).Id,
DisplayOrder = 1,
CreatedOnUtc = DateTime.UtcNow,
UpdatedOnUtc = DateTime.UtcNow
@@ -7080,7 +7083,7 @@ protected virtual void InstallManufacturers()
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
Published = true,
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "manufacturer_hp.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Hp")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "manufacturer_hp.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Hp")).Id,
DisplayOrder = 5,
CreatedOnUtc = DateTime.UtcNow,
UpdatedOnUtc = DateTime.UtcNow
@@ -7096,7 +7099,7 @@ protected virtual void InstallManufacturers()
AllowCustomersToSelectPageSize = true,
PageSizeOptions = "6, 3, 9",
Published = true,
- PictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "manufacturer_nike.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Nike")).Id,
+ PictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "manufacturer_nike.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Nike")).Id,
DisplayOrder = 5,
CreatedOnUtc = DateTime.UtcNow,
UpdatedOnUtc = DateTime.UtcNow
@@ -7336,12 +7339,12 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productBuildComputer);
productBuildComputer.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_Desktops_1.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productBuildComputer.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_Desktops_1.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productBuildComputer.Name)),
DisplayOrder = 1,
});
productBuildComputer.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_Desktops_2.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productBuildComputer.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_Desktops_2.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productBuildComputer.Name)),
DisplayOrder = 2,
});
_productRepository.Insert(productBuildComputer);
@@ -7388,7 +7391,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productDigitalStorm);
productDigitalStorm.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_DigitalStorm.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productDigitalStorm.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_DigitalStorm.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productDigitalStorm.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productDigitalStorm);
@@ -7435,7 +7438,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productLenovoIdeaCentre);
productLenovoIdeaCentre.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_LenovoIdeaCentre.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productLenovoIdeaCentre.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_LenovoIdeaCentre.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productLenovoIdeaCentre.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productLenovoIdeaCentre);
@@ -7527,12 +7530,12 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productAppleMacBookPro);
productAppleMacBookPro.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_macbook_1.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productAppleMacBookPro.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_macbook_1.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productAppleMacBookPro.Name)),
DisplayOrder = 1,
});
productAppleMacBookPro.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_macbook_2.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productAppleMacBookPro.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_macbook_2.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productAppleMacBookPro.Name)),
DisplayOrder = 2,
});
_productRepository.Insert(productAppleMacBookPro);
@@ -7610,7 +7613,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productAsusN551JK);
productAsusN551JK.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_asuspc_N551JK.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productAsusN551JK.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_asuspc_N551JK.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productAsusN551JK.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productAsusN551JK);
@@ -7689,7 +7692,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productSamsungSeries);
productSamsungSeries.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_SamsungNP900X4C.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productSamsungSeries.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_SamsungNP900X4C.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productSamsungSeries.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productSamsungSeries);
@@ -7775,12 +7778,12 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productHpSpectre);
productHpSpectre.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_HPSpectreXT_1.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productHpSpectre.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_HPSpectreXT_1.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productHpSpectre.Name)),
DisplayOrder = 1,
});
productHpSpectre.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_HPSpectreXT_2.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productHpSpectre.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_HPSpectreXT_2.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productHpSpectre.Name)),
DisplayOrder = 2,
});
_productRepository.Insert(productHpSpectre);
@@ -7866,7 +7869,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productHpEnvy);
productHpEnvy.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_HpEnvy6.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productHpEnvy.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_HpEnvy6.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productHpEnvy.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productHpEnvy);
@@ -7930,7 +7933,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productLenovoThinkpad);
productLenovoThinkpad.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_LenovoThinkpad.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productLenovoThinkpad.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_LenovoThinkpad.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productLenovoThinkpad.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productLenovoThinkpad);
@@ -7981,7 +7984,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productAdobePhotoshop);
productAdobePhotoshop.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_AdobePhotoshop.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productAdobePhotoshop.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_AdobePhotoshop.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productAdobePhotoshop.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productAdobePhotoshop);
@@ -8028,7 +8031,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productWindows8Pro);
productWindows8Pro.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_Windows8.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productWindows8Pro.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_Windows8.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productWindows8Pro.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productWindows8Pro);
@@ -8079,7 +8082,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productSoundForge);
productSoundForge.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_SoundForge.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productSoundForge.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_SoundForge.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productSoundForge.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productSoundForge);
@@ -8131,12 +8134,12 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productNikonD5500DSLR);
productNikonD5500DSLR.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_NikonCamera_1.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productNikonD5500DSLR.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_NikonCamera_1.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productNikonD5500DSLR.Name)),
DisplayOrder = 1,
});
productNikonD5500DSLR.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_NikonCamera_2.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productNikonD5500DSLR.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_NikonCamera_2.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productNikonD5500DSLR.Name)),
DisplayOrder = 2,
});
_productRepository.Insert(productNikonD5500DSLR);
@@ -8173,7 +8176,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productNikonD5500DSLR_associated_1);
productNikonD5500DSLR_associated_1.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_NikonCamera_black.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Canon Digital SLR Camera - Black")),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_NikonCamera_black.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Canon Digital SLR Camera - Black")),
DisplayOrder = 1,
});
_productRepository.Insert(productNikonD5500DSLR_associated_1);
@@ -8210,7 +8213,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productNikonD5500DSLR_associated_2);
productNikonD5500DSLR_associated_2.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_NikonCamera_red.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Canon Digital SLR Camera - Silver")),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_NikonCamera_red.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName("Canon Digital SLR Camera - Silver")),
DisplayOrder = 1,
});
_productRepository.Insert(productNikonD5500DSLR_associated_2);
@@ -8257,7 +8260,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productLeica);
productLeica.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_LeicaT.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productLeica.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_LeicaT.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productLeica.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productLeica);
@@ -8312,7 +8315,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productAppleICam);
productAppleICam.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_iCam.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productAppleICam.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_iCam.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productAppleICam.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productAppleICam);
@@ -8365,7 +8368,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productHtcOne);
productHtcOne.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_HTC_One_M8.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productHtcOne.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_HTC_One_M8.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productHtcOne.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productHtcOne);
@@ -8413,12 +8416,12 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productHtcOneMini);
productHtcOneMini.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_HTC_One_Mini_1.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productHtcOneMini.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_HTC_One_Mini_1.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productHtcOneMini.Name)),
DisplayOrder = 1,
});
productHtcOneMini.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_HTC_One_Mini_2.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productHtcOneMini.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_HTC_One_Mini_2.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productHtcOneMini.Name)),
DisplayOrder = 2,
});
_productRepository.Insert(productHtcOneMini);
@@ -8465,7 +8468,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productNokiaLumia);
productNokiaLumia.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_Lumia1020.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productNokiaLumia.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_Lumia1020.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productNokiaLumia.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productNokiaLumia);
@@ -8539,12 +8542,12 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productBeatsPill);
productBeatsPill.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_PillBeats_1.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productBeatsPill.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_PillBeats_1.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productBeatsPill.Name)),
DisplayOrder = 1,
});
productBeatsPill.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_PillBeats_2.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productBeatsPill.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_PillBeats_2.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productBeatsPill.Name)),
DisplayOrder = 2,
});
_productRepository.Insert(productBeatsPill);
@@ -8591,7 +8594,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productUniversalTabletCover);
productUniversalTabletCover.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_TabletCover.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productUniversalTabletCover.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_TabletCover.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productUniversalTabletCover.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productUniversalTabletCover);
@@ -8638,7 +8641,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productPortableSoundSpeakers);
productPortableSoundSpeakers.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_Speakers.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productPortableSoundSpeakers.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_Speakers.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productPortableSoundSpeakers.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productPortableSoundSpeakers);
@@ -8745,14 +8748,14 @@ protected virtual void InstallProducts(string defaultUserEmail)
AttributeValueType = AttributeValueType.Simple,
Name = "Natural",
DisplayOrder = 1,
- ImageSquaresPictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "p_attribute_print_2.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Natural Print")).Id,
+ ImageSquaresPictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "p_attribute_print_2.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Natural Print")).Id,
},
new ProductAttributeValue
{
AttributeValueType = AttributeValueType.Simple,
Name = "Fresh",
DisplayOrder = 2,
- ImageSquaresPictureId = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "p_attribute_print_1.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Fresh Print")).Id,
+ ImageSquaresPictureId = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "p_attribute_print_1.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName("Fresh Print")).Id,
},
}
}
@@ -8789,12 +8792,12 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productNikeFloral);
productNikeFloral.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_NikeFloralShoe_1.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productNikeFloral.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_NikeFloralShoe_1.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productNikeFloral.Name)),
DisplayOrder = 1,
});
productNikeFloral.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_NikeFloralShoe_2.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productNikeFloral.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_NikeFloralShoe_2.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productNikeFloral.Name)),
DisplayOrder = 2,
});
_productRepository.Insert(productNikeFloral);
@@ -8943,17 +8946,17 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productAdidas);
productAdidas.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_adidas.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productAdidas.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_adidas.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productAdidas.Name)),
DisplayOrder = 1,
});
productAdidas.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_adidas_2.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productAdidas.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_adidas_2.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productAdidas.Name)),
DisplayOrder = 2,
});
productAdidas.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_adidas_3.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productAdidas.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_adidas_3.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productAdidas.Name)),
DisplayOrder = 3,
});
@@ -9027,7 +9030,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productNikeZoom);
productNikeZoom.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_NikeZoom.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productNikeZoom.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_NikeZoom.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productNikeZoom.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productNikeZoom);
@@ -9134,7 +9137,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productNikeTailwind);
productNikeTailwind.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_NikeShirt.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productNikeTailwind.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_NikeShirt.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productNikeTailwind.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productNikeTailwind);
@@ -9200,7 +9203,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productOversizedWomenTShirt);
productOversizedWomenTShirt.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_WomenTShirt.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productOversizedWomenTShirt.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_WomenTShirt.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productOversizedWomenTShirt.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productOversizedWomenTShirt);
@@ -9257,7 +9260,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productCustomTShirt);
productCustomTShirt.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_CustomTShirt.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productCustomTShirt.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_CustomTShirt.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productCustomTShirt.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productCustomTShirt);
@@ -9325,12 +9328,12 @@ protected virtual void InstallProducts(string defaultUserEmail)
productLeviJeans.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_LeviJeans_1.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productLeviJeans.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_LeviJeans_1.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productLeviJeans.Name)),
DisplayOrder = 1,
});
productLeviJeans.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_LeviJeans_2.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productLeviJeans.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_LeviJeans_2.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productLeviJeans.Name)),
DisplayOrder = 2,
});
_productRepository.Insert(productLeviJeans);
@@ -9417,7 +9420,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productObeyHat);
productObeyHat.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_hat.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productObeyHat.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_hat.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productObeyHat.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productObeyHat);
@@ -9465,7 +9468,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productBelt);
productBelt.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_Belt.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productBelt.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_Belt.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productBelt.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productBelt);
@@ -9512,7 +9515,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productSunglasses);
productSunglasses.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_Sunglasses.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productSunglasses.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_Sunglasses.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productSunglasses.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productSunglasses);
@@ -9525,7 +9528,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
{
DownloadGuid = Guid.NewGuid(),
ContentType = MimeTypes.ApplicationXZipCo,
- DownloadBinary = File.ReadAllBytes(sampleDownloadsPath + "product_NightVision_1.zip"),
+ DownloadBinary = _fileProvider.ReadAllBytes(sampleDownloadsPath + "product_NightVision_1.zip"),
Extension = ".zip",
Filename = "Night_Vision_1",
IsNew = true,
@@ -9535,7 +9538,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
{
DownloadGuid = Guid.NewGuid(),
ContentType = MimeTypes.TextPlain,
- DownloadBinary = File.ReadAllBytes(sampleDownloadsPath + "product_NightVision_2.txt"),
+ DownloadBinary = _fileProvider.ReadAllBytes(sampleDownloadsPath + "product_NightVision_2.txt"),
Extension = ".txt",
Filename = "Night_Vision_1",
IsNew = true,
@@ -9585,7 +9588,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productNightVision);
productNightVision.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_NightVisions.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productNightVision.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_NightVisions.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productNightVision.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productNightVision);
@@ -9594,7 +9597,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
{
DownloadGuid = Guid.NewGuid(),
ContentType = MimeTypes.ApplicationXZipCo,
- DownloadBinary = File.ReadAllBytes(sampleDownloadsPath + "product_IfYouWait_1.zip"),
+ DownloadBinary = _fileProvider.ReadAllBytes(sampleDownloadsPath + "product_IfYouWait_1.zip"),
Extension = ".zip",
Filename = "If_You_Wait_1",
IsNew = true,
@@ -9604,7 +9607,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
{
DownloadGuid = Guid.NewGuid(),
ContentType = MimeTypes.TextPlain,
- DownloadBinary = File.ReadAllBytes(sampleDownloadsPath + "product_IfYouWait_2.txt"),
+ DownloadBinary = _fileProvider.ReadAllBytes(sampleDownloadsPath + "product_IfYouWait_2.txt"),
Extension = ".txt",
Filename = "If_You_Wait_1",
IsNew = true,
@@ -9657,7 +9660,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
productIfYouWait.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_IfYouWait.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productIfYouWait.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_IfYouWait.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productIfYouWait.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productIfYouWait);
@@ -9666,7 +9669,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
{
DownloadGuid = Guid.NewGuid(),
ContentType = MimeTypes.ApplicationXZipCo,
- DownloadBinary = File.ReadAllBytes(sampleDownloadsPath + "product_ScienceAndFaith_1.zip"),
+ DownloadBinary = _fileProvider.ReadAllBytes(sampleDownloadsPath + "product_ScienceAndFaith_1.zip"),
Extension = ".zip",
Filename = "Science_And_Faith",
IsNew = true,
@@ -9717,7 +9720,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productScienceAndFaith);
productScienceAndFaith.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_ScienceAndFaith.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productScienceAndFaith.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_ScienceAndFaith.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productScienceAndFaith.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productScienceAndFaith);
@@ -9770,7 +9773,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productFahrenheit);
productFahrenheit.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_Fahrenheit451.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productFahrenheit.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_Fahrenheit451.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productFahrenheit.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productFahrenheit);
@@ -9818,7 +9821,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productFirstPrizePies);
productFirstPrizePies.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_FirstPrizePies.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productFirstPrizePies.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_FirstPrizePies.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productFirstPrizePies.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productFirstPrizePies);
@@ -9866,7 +9869,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productPrideAndPrejudice);
productPrideAndPrejudice.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_PrideAndPrejudice.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productPrideAndPrejudice.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_PrideAndPrejudice.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(productPrideAndPrejudice.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productPrideAndPrejudice);
@@ -9921,7 +9924,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productElegantGemstoneNecklace);
productElegantGemstoneNecklace.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_GemstoneNecklaces.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productElegantGemstoneNecklace.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_GemstoneNecklaces.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productElegantGemstoneNecklace.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productElegantGemstoneNecklace);
@@ -9969,7 +9972,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productFlowerGirlBracelet);
productFlowerGirlBracelet.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_FlowerBracelet.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productFlowerGirlBracelet.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_FlowerBracelet.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productFlowerGirlBracelet.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productFlowerGirlBracelet);
@@ -10016,7 +10019,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(productEngagementRing);
productEngagementRing.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_EngagementRing_1.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productEngagementRing.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_EngagementRing_1.jpg"), MimeTypes.ImagePJpeg, pictureService.GetPictureSeName(productEngagementRing.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(productEngagementRing);
@@ -10061,7 +10064,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(product25GiftCard);
product25GiftCard.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_25giftcart.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(product25GiftCard.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_25giftcart.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(product25GiftCard.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(product25GiftCard);
@@ -10109,7 +10112,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(product50GiftCard);
product50GiftCard.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_50giftcart.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(product50GiftCard.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_50giftcart.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(product50GiftCard.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(product50GiftCard);
@@ -10155,7 +10158,7 @@ protected virtual void InstallProducts(string defaultUserEmail)
allProducts.Add(product100GiftCard);
product100GiftCard.ProductPictures.Add(new ProductPicture
{
- Picture = pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "product_100giftcart.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(product100GiftCard.Name)),
+ Picture = pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "product_100giftcart.jpeg"), MimeTypes.ImageJpeg, pictureService.GetPictureSeName(product100GiftCard.Name)),
DisplayOrder = 1,
});
_productRepository.Insert(product100GiftCard);
diff --git a/src/Libraries/Nop.Services/Installation/SqlFileInstallationService.cs b/src/Libraries/Nop.Services/Installation/SqlFileInstallationService.cs
index 9ab1f1ccf9d..9f6648b86b4 100644
--- a/src/Libraries/Nop.Services/Installation/SqlFileInstallationService.cs
+++ b/src/Libraries/Nop.Services/Installation/SqlFileInstallationService.cs
@@ -27,6 +27,7 @@ public partial class SqlFileInstallationService : IInstallationService
private readonly IRepository _storeRepository;
private readonly IDbContext _dbContext;
private readonly IWebHelper _webHelper;
+ private readonly INopFileProvider _fileProvider;
#endregion
@@ -40,17 +41,20 @@ public partial class SqlFileInstallationService : IInstallationService
/// Store repository
/// DB context
/// Web helper
+ /// File provider
public SqlFileInstallationService(IRepository languageRepository,
IRepository customerRepository,
IRepository storeRepository,
IDbContext dbContext,
- IWebHelper webHelper)
+ IWebHelper webHelper,
+ INopFileProvider fileProvider)
{
this._languageRepository = languageRepository;
this._customerRepository = customerRepository;
this._storeRepository = storeRepository;
this._dbContext = dbContext;
this._webHelper = webHelper;
+ this._fileProvider = fileProvider;
}
#endregion
@@ -66,9 +70,9 @@ protected virtual void InstallLocaleResources()
var language = _languageRepository.Table.Single(l => l.Name == "English");
//save resources
- foreach (var filePath in System.IO.Directory.EnumerateFiles(CommonHelper.MapPath("~/App_Data/Localization/"), "*.nopres.xml", SearchOption.TopDirectoryOnly))
+ foreach (var filePath in _fileProvider.EnumerateFiles(_fileProvider.MapPath("~/App_Data/Localization/"), "*.nopres.xml"))
{
- var localesXml = File.ReadAllText(filePath);
+ var localesXml = _fileProvider.ReadAllText(filePath, Encoding.UTF8);
var localizationService = EngineContext.Current.Resolve();
localizationService.ImportResourcesFromXml(language, localesXml);
}
@@ -115,9 +119,8 @@ protected virtual void UpdateDefaultStoreUrl()
protected virtual void ExecuteSqlFile(string path)
{
var statements = new List();
-
- using (var stream = File.OpenRead(path))
- using (var reader = new StreamReader(stream))
+
+ using (var reader = new StreamReader(path))
{
string statement;
while ((statement = ReadNextStatementFromStream(reader)) != null)
@@ -169,14 +172,14 @@ protected virtual string ReadNextStatementFromStream(StreamReader reader)
public virtual void InstallData(string defaultUserEmail,
string defaultUserPassword, bool installSampleData = true)
{
- ExecuteSqlFile(CommonHelper.MapPath("~/App_Data/Install/Fast/create_required_data.sql"));
+ ExecuteSqlFile(_fileProvider.MapPath("~/App_Data/Install/Fast/create_required_data.sql"));
InstallLocaleResources();
UpdateDefaultCustomer(defaultUserEmail, defaultUserPassword);
UpdateDefaultStoreUrl();
if (installSampleData)
{
- ExecuteSqlFile(CommonHelper.MapPath("~/App_Data/Install/Fast/create_sample_data.sql"));
+ ExecuteSqlFile(_fileProvider.MapPath("~/App_Data/Install/Fast/create_sample_data.sql"));
}
}
diff --git a/src/Libraries/Nop.Services/Media/AzurePictureService.cs b/src/Libraries/Nop.Services/Media/AzurePictureService.cs
index 13dea78ce21..ffc44b8ff61 100644
--- a/src/Libraries/Nop.Services/Media/AzurePictureService.cs
+++ b/src/Libraries/Nop.Services/Media/AzurePictureService.cs
@@ -1,7 +1,6 @@
using System;
using System.Linq;
using System.Threading.Tasks;
-using Microsoft.AspNetCore.Hosting;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Nop.Core;
@@ -10,6 +9,7 @@
using Nop.Core.Data;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Media;
+using Nop.Core.Infrastructure;
using Nop.Data;
using Nop.Services.Configuration;
using Nop.Services.Events;
@@ -64,7 +64,7 @@ public partial class AzurePictureService : PictureService
/// Media settings
/// Config
/// Data provider
- /// Hosting environment
+ /// File provider
public AzurePictureService(IRepository