/// <summary> /// Сopy the directory with the embedded files and directories /// </summary> /// <param name="sourcePath">Path to the source directory</param> /// <param name="destinationPath">Path to the destination directory</param> protected virtual void CopyDirectory(string sourcePath, string destinationPath) { var existingFiles = _fileProvider.GetFiles(sourcePath); var existingDirectories = _fileProvider.GetDirectories(sourcePath); if (!_fileProvider.DirectoryExists(destinationPath)) { _fileProvider.CreateDirectory(destinationPath); } foreach (var file in existingFiles) { var filePath = _fileProvider.Combine(destinationPath, _fileProvider.GetFileName(file)); if (!_fileProvider.FileExists(filePath)) { _fileProvider.FileCopy(file, filePath); } } foreach (var directory in existingDirectories) { var directoryPath = _fileProvider.Combine(destinationPath, _fileProvider.GetDirectoryName(directory)); CopyDirectory(directory, directoryPath); } }
/// <summary> /// Get picture (thumb) local path /// </summary> /// <param name="thumbFileName">Filename</param> /// <returns>Local picture thumb path</returns> protected virtual string GetThumbLocalPath(string thumbFileName) { var thumbsDirectoryPath = _fileProvider.GetAbsolutePath(NopMediaDefaults.ImageThumbsPath); if (_mediaSettings.MultipleThumbDirectories) { //get the first two letters of the file name var fileNameWithoutExtension = _fileProvider.GetFileNameWithoutExtension(thumbFileName); if (fileNameWithoutExtension != null && fileNameWithoutExtension.Length > NopMediaDefaults.MultipleThumbDirectoriesLength) { var subDirectoryName = fileNameWithoutExtension.Substring(0, NopMediaDefaults.MultipleThumbDirectoriesLength); thumbsDirectoryPath = _fileProvider.GetAbsolutePath(NopMediaDefaults.ImageThumbsPath, subDirectoryName); _fileProvider.CreateDirectory(thumbsDirectoryPath); } } var thumbFilePath = _fileProvider.Combine(thumbsDirectoryPath, thumbFileName); if (thumbFilePath.ToLower().Contains("localhost")) { thumbFilePath = thumbFilePath.Replace("localhost", PublicIP); } return(thumbFilePath); }
/// <summary> /// Save a value indicating whether some file (thumb) already exists /// </summary> /// <param name="thumbFilePath">Thumb file path</param> /// <param name="thumbFileName">Thumb file name</param> /// <param name="mimeType">MIME type</param> /// <param name="binary">Picture binary</param> protected virtual void SaveThumb(string thumbFilePath, string thumbFileName, string mimeType, byte[] binary) { //ensure \thumb directory exists var thumbsDirectoryPath = _fileProvider.GetAbsolutePath(NopMediaDefaults.ImageThumbsPath); _fileProvider.CreateDirectory(thumbsDirectoryPath); //save _fileProvider.WriteAllBytes(thumbFilePath, binary); }
public string GetLuceneDirectory() { var path = _fileProvider.MapPath($"~/App_Data/{Constants.LUCENE_DIRECTORY_NAME}"); _fileProvider.CreateDirectory(path); return(path); }
private string DownloadFile(string urlString, IList <string> downloadedFiles) { if (string.IsNullOrEmpty(urlString)) { return(string.Empty); } if (!Uri.IsWellFormedUriString(urlString, UriKind.Absolute)) { return(urlString); } //ensure that temp directory is created var tempDirectory = _fileProvider.MapPath(UPLOADS_TEMP_PATH); _fileProvider.CreateDirectory(tempDirectory); var fileName = _fileProvider.GetFileName(urlString); if (string.IsNullOrEmpty(fileName)) { return(string.Empty); } var filePath = _fileProvider.Combine(tempDirectory, fileName); try { WebRequest.Create(urlString); } catch { return(string.Empty); } try { byte[] fileData; using (var client = new WebClient()) { fileData = client.DownloadData(urlString); } using (var fs = new FileStream(filePath, FileMode.OpenOrCreate)) { fs.Write(fileData, 0, fileData.Length); } downloadedFiles?.Add(filePath); return(filePath); } catch (Exception ex) { _logger.Error("Download image failed", ex); } return(string.Empty); }
/// <summary> /// Get directory path for backs /// </summary> /// <param name="ensureFolderCreated">A value indicating whether a directory should be created if it doesn't exist</param> /// <returns></returns> protected virtual string GetBackupDirectoryPath(bool ensureFolderCreated = true) { var path = _fileProvider.GetAbsolutePath(NopCommonDefaults.DbBackupsPath); if (ensureFolderCreated) { _fileProvider.CreateDirectory(path); } return(path); }
/// <summary> /// Get directory path for backs /// </summary> /// <param name="ensureFolderCreated">A value indicating whether a directory should be created if it doesn't exist</param> /// <returns></returns> protected virtual string GetBackupDirectoryPath(bool ensureFolderCreated = true) { var path = _fileProvider.GetAbsolutePath("db_backups\\"); if (ensureFolderCreated) { _fileProvider.CreateDirectory(path); } return(path); }
/// <summary> /// Get picture (thumb) local path /// </summary> /// <param name="thumbFileName">Filename</param> /// <returns>Local picture thumb path</returns> protected virtual string GetThumbLocalPath(string thumbFileName) { var thumbsDirectoryPath = _fileProvider.GetAbsolutePath(THUMBS_PATH); if (_mediaSettings.MultipleThumbDirectories) { //get the first two letters of the file name var fileNameWithoutExtension = _fileProvider.GetFileNameWithoutExtension(thumbFileName); if (fileNameWithoutExtension != null && fileNameWithoutExtension.Length > MULTIPLE_THUMB_DIRECTORIES_LENGTH) { var subDirectoryName = fileNameWithoutExtension.Substring(0, MULTIPLE_THUMB_DIRECTORIES_LENGTH); thumbsDirectoryPath = _fileProvider.GetAbsolutePath(THUMBS_PATH, subDirectoryName); _fileProvider.CreateDirectory(thumbsDirectoryPath); } } var thumbFilePath = _fileProvider.Combine(thumbsDirectoryPath, thumbFileName); return(thumbFilePath); }
/// <summary> /// Perform file deploy /// </summary> /// <param name="plug">Plugin file info</param> /// <param name="applicationPartManager">Application part manager</param> /// <param name="config">Config</param> /// <param name="shadowCopyPath">Shadow copy path</param> /// <returns>Assembly</returns> private static Assembly PerformFileDeploy(string plug, ApplicationPartManager applicationPartManager, NopConfig config, string shadowCopyPath = "") { 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; } _fileProvider.CreateDirectory(shadowCopyPath); var shadowCopiedPlug = ShadowCopyFile(plug, shadowCopyPath); Assembly shadowCopiedAssembly = null; try { shadowCopiedAssembly = RegisterPluginDefinition(config, applicationPartManager, shadowCopiedPlug); } catch (FileLoadException) { if (!config.CopyLockedPluginAssembilesToSubdirectoriesOnStartup || !shadowCopyPath.Equals(_shadowCopyFolder)) { throw; } } return(shadowCopiedAssembly ?? PerformFileDeploy(plug, applicationPartManager, config, _reserveShadowCopyFolder)); }
/// <summary> /// Create OrderPayments directory and create file and save code in it /// </summary> /// <param name="result">Html code</param> public string PutHtmlCodeInFile(string result) { //Create OrderPayments directory if not excist var dir = $"{_webHostEnvironment.WebRootPath}\\{KuveytTurkDefaults.OrderPaymentsDirectory}"; _nopFileProvider.CreateDirectory(dir); //Write result to file and create if not excist var file = "tmp" + DateTime.UtcNow.Ticks + "{" + _workContext.CurrentCustomer.Id + "}.html"; _nopFileProvider.WriteAllText($"{dir}\\{file}", result, Encoding.UTF8); return(file); }
/// <summary> /// Initialize /// </summary> /// <param name="applicationPartManager">Application part manager</param> /// <param name="config">Config</param> public static void Initialize(IPerformDeploy performDeploy, NopConfig config) { if (performDeploy == null) { throw new ArgumentNullException(nameof(performDeploy)); } if (config == null) { throw new ArgumentNullException(nameof(config)); } using (new WriteLockDisposable(Locker)) { // TODO: Add verbose exception handling / raising here since this is happening on app startup and could // prevent app from starting altogether 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 <PluginDescriptor>(); var incompatiblePlugins = new List <string>(); try { var installedPluginSystemNames = GetInstalledPluginNames(_fileProvider.MapPath(InstalledPluginsFilePath)); Debug.WriteLine("Creating shadow copy folder and querying for DLLs"); //ensure folders are created _fileProvider.CreateDirectory(pluginFolder); _fileProvider.CreateDirectory(_shadowCopyFolder); //get list of all files in bin var binFiles = _fileProvider.GetFiles(_shadowCopyFolder, "*", false); if (config.ClearPluginShadowDirectoryOnStartup) { //clear out shadow copied plugins foreach (var f in binFiles) { if (_fileProvider.GetFileName(f).Equals("placeholder.txt", StringComparison.InvariantCultureIgnoreCase)) { continue; } Debug.WriteLine("Deleting " + f); try { //ignore index.htm var fileName = _fileProvider.GetFileName(f); if (fileName.Equals("index.htm", StringComparison.InvariantCultureIgnoreCase)) { continue; } _fileProvider.DeleteFile(f); } catch (Exception exc) { Debug.WriteLine("Error deleting file " + f + ". Exception: " + exc); } } //delete all reserve folders foreach (var directory in _fileProvider.GetDirectories(_shadowCopyFolder, RESERVE_SHADOW_COPY_FOLDER_NAME_PATTERN)) { try { _fileProvider.DeleteDirectory(directory); } catch { //do nothing } } } //load description files foreach (var dfd in GetDescriptionFilesAndDescriptors(pluginFolder)) { var descriptionFile = dfd.Key; var pluginDescriptor = dfd.Value; //ensure that version of plugin is valid if (!pluginDescriptor.SupportedVersions.Contains(NopVersion.CurrentVersion, StringComparer.InvariantCultureIgnoreCase)) { incompatiblePlugins.Add(pluginDescriptor.SystemName); continue; } //some validation if (string.IsNullOrWhiteSpace(pluginDescriptor.SystemName)) { 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"); } //set 'Installed' property pluginDescriptor.Installed = installedPluginSystemNames .FirstOrDefault(x => x.Equals(pluginDescriptor.SystemName, StringComparison.InvariantCultureIgnoreCase)) != null; try { 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 = _fileProvider.GetFiles(directoryName, "*.dll", false) //just make sure we're not registering shadow copied plugins .Where(x => !binFiles.Select(q => q).Contains(x)) .Where(x => IsPackagePluginFolder(_fileProvider.GetDirectoryName(x))) .ToList(); //other plugin description info var mainPluginFile = pluginFiles .FirstOrDefault(x => _fileProvider.GetFileName(x).Equals(pluginDescriptor.AssemblyFileName, StringComparison.InvariantCultureIgnoreCase)); //plugin have wrong directory if (mainPluginFile == null) { incompatiblePlugins.Add(pluginDescriptor.SystemName); continue; } pluginDescriptor.OriginalAssemblyFile = mainPluginFile; //shadow copy main plugin file pluginDescriptor.ReferencedAssembly = performDeploy.PerformFileDeploy(mainPluginFile, config); //load all other referenced assemblies now foreach (var plugin in pluginFiles .Where(x => !_fileProvider.GetFileName(x).Equals(_fileProvider.GetFileName(mainPluginFile), StringComparison.InvariantCultureIgnoreCase)) .Where(x => !IsAlreadyLoaded(x))) { performDeploy.PerformFileDeploy(plugin, config); } //init plugin type (only one plugin per assembly is allowed) foreach (var t in pluginDescriptor.ReferencedAssembly.GetTypes()) { if (typeof(IPlugin).IsAssignableFrom(t)) { if (!t.IsInterface) { if (t.IsClass && !t.IsAbstract) { pluginDescriptor.PluginType = t; break; } } } } referencedPlugins.Add(pluginDescriptor); } catch (ReflectionTypeLoadException ex) { //add a plugin name. this way we can easily identify a problematic plugin var msg = $"Plugin '{pluginDescriptor.FriendlyName}'. "; foreach (var e in ex.LoaderExceptions) { msg += e.Message + Environment.NewLine; } var fail = new Exception(msg, ex); throw fail; } catch (Exception ex) { //add a plugin name. this way we can easily identify a problematic plugin var msg = $"Plugin '{pluginDescriptor.FriendlyName}'. {ex.Message}"; var fail = new Exception(msg, ex); throw fail; } } } catch (Exception ex) { var msg = string.Empty; for (var e = ex; e != null; e = e.InnerException) { msg += e.Message + Environment.NewLine; } var fail = new Exception(msg, ex); throw fail; } ReferencedPlugins = referencedPlugins; IncompatiblePlugins = incompatiblePlugins; } }