public void SaveToSource(string name, IDictionary <string, string> configuration) { var settingsFile = GetSettingsFilePath(PathExtensions.Combine( _optionsAccessor.Value.ShellsApplicationDataPath, _optionsAccessor.Value.ShellsContainerName, name)); var configurationProvider = new YamlConfigurationProvider(new YamlConfigurationSource { Path = settingsFile, Optional = false }); configurationProvider.Set(name, null); configurationProvider.Set($"{name}:RequestUrlHost", ObtainValue(configuration, $"{name}:RequestUrlHost")); configurationProvider.Set($"{name}:RequestUrlPrefix", ObtainValue(configuration, $"{name}:RequestUrlPrefix")); configurationProvider.Set($"{name}:DatabaseProvider", ObtainValue(configuration, $"{name}:DatabaseProvider")); configurationProvider.Set($"{name}:TablePrefix", ObtainValue(configuration, $"{name}:TablePrefix")); configurationProvider.Set($"{name}:ConnectionString", ObtainValue(configuration, $"{name}:ConnectionString")); configurationProvider.Set($"{name}:State", ObtainValue(configuration, $"{name}:State")); configurationProvider.Set($"{name}:Secret", ObtainValue(configuration, $"{name}:Secret")); configurationProvider.Set($"{name}:RecipeName", ObtainValue(configuration, $"{name}:RecipeName")); configurationProvider.Commit(); }
/// <summary> /// Converts file paths to absolute paths. /// </summary> private static bool ResolveFilePath(PluginBuilder builder, string builderFilePath) { string builderDirectory = Path.GetDirectoryName(builderFilePath); bool success = true; foreach (var file in builder.files) { if (File.Exists(file.source)) { if (!Path.IsPathRooted(file.source)) { file.source = Path.GetFullPath(file.source); } } else { string fromBuildDir = PathExtensions.Combine(builderDirectory, file.source); if (File.Exists(fromBuildDir)) { file.source = Path.GetFullPath(fromBuildDir); } else { success = false; Logger.WriteLine("Could not locate the file: " + Path.GetFileName(file.source), logTo: Logger.LogTo.File | Logger.LogTo.StandardOut); Logger.WriteLine("\tNot at " + Path.GetFullPath(file.source), logTo: Logger.LogTo.File | Logger.LogTo.StandardOut); Logger.WriteLine("\tNot at " + Path.GetFullPath(fromBuildDir), logTo: Logger.LogTo.File | Logger.LogTo.StandardOut); } } } return(success); }
public async Task <IActionResult> Execute(int id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.Export)) { return(Unauthorized()); } var deploymentPlan = await _session.GetAsync <DeploymentPlan>(id); if (deploymentPlan == null) { return(NotFound()); } string archiveFileName; var filename = deploymentPlan.Name.ToSafeName() + ".zip"; using (var fileBuilder = new TemporaryFileBuilder()) { archiveFileName = PathExtensions.Combine(Path.GetTempPath(), filename); var deploymentPlanResult = new DeploymentPlanResult(fileBuilder); await _deploymentManager.ExecuteDeploymentPlanAsync(deploymentPlan, deploymentPlanResult); ZipFile.CreateFromDirectory(fileBuilder.Folder, archiveFileName); } return(new PhysicalFileResult(archiveFileName, "application/zip") { FileDownloadName = filename }); }
public LuceneIndexManager( IClock clock, IOptions <ShellOptions> shellOptions, ShellSettings shellSettings, ILogger <LuceneIndexManager> logger, LuceneAnalyzerManager luceneAnalyzerManager, LuceneIndexSettingsService luceneIndexSettingsService ) { _clock = clock; _logger = logger; _rootPath = PathExtensions.Combine( shellOptions.Value.ShellsApplicationDataPath, shellOptions.Value.ShellsContainerName, shellSettings.Name, "Lucene"); Directory.CreateDirectory(_rootPath); _luceneAnalyzerManager = luceneAnalyzerManager; _luceneIndexSettingsService = luceneIndexSettingsService; // Typical geospatial context // These can also be constructed from SpatialContextFactory _ctx = SpatialContext.Geo; var maxLevels = 11; // Results in sub-meter precision for geohash // TODO demo lookup by detail distance // This can also be constructed from SpatialPrefixTreeFactory _grid = new GeohashPrefixTree(_ctx, maxLevels); }
public void DeleteIndex(string indexName) { lock (this) { if (_writers.TryGetValue(indexName, out var writer)) { writer.IsClosing = true; writer.Dispose(); } if (_indexPools.TryRemove(indexName, out var reader)) { reader.Dispose(); } _timestamps.TryRemove(indexName, out _); var indexFolder = PathExtensions.Combine(_rootPath, indexName); if (Directory.Exists(indexFolder)) { try { Directory.Delete(indexFolder, true); } catch { } } _writers.TryRemove(indexName, out _); } }
private void HandleGETRequest() { foreach (KeyValuePair <string, CompiledScriptRequestHandler> csrh in this.m_Server.CompiledRequestHandlers) { if (csrh.Key == this.RequestData.URL) { csrh.Value(this); return; } } CachedFile file = null; if (this.m_Server.UseCache) { file = this.m_Server.Cache.GetFile(PathExtensions.Combine(this.m_Server.HomeDirectory, this.RequestData.LocalURL)); } else { file = new CachedFile() { FileName = PathExtensions.Combine(this.m_Server.HomeDirectory, this.RequestData.LocalURL) }; file.ReadFileContents(); } if (file.Valid) { this.WriteSuccess(); this.OutputStream.BaseStream.Write(file.Data, 0, file.Data.Length); } else { this.WriteFailure(); } }
public IEnumerable <IFileInfo> GetLocations(string cultureName) { var poFileName = cultureName + PoFileExtension; var extensions = _extensionsManager.GetExtensions(); // Load .po files in each extension folder first, based on the extensions order foreach (var extension in extensions) { yield return(_fileProvider.GetFileInfo(PathExtensions.Combine(extension.SubPath, ExtensionDataFolder, _resourcesContainer, poFileName))); } // Then load global .po file for the applications yield return(new PhysicalFileInfo(new FileInfo(PathExtensions.Combine(_applicationDataContainer, _resourcesContainer, poFileName)))); // Load tenant-specific .po file yield return(new PhysicalFileInfo(new FileInfo(PathExtensions.Combine(_shellDataContainer, _resourcesContainer, poFileName)))); // Load each modules .po file for extending localization when using Orchard Core as a Nuget package foreach (var extension in extensions) { // \src\OrchardCore.Cms.Web\App_Data/Localization/OrchardCore.Cms.Web/fr-CA.po yield return(new PhysicalFileInfo(new FileInfo(PathExtensions.Combine(_applicationDataContainer, _resourcesContainer, extension.Id, poFileName)))); // \src\OrchardCore.Cms.Web\App_Data/Localization/OrchardCore.Cms.Web-fr-CA.po yield return(new PhysicalFileInfo(new FileInfo(PathExtensions.Combine(_applicationDataContainer, _resourcesContainer, extension.Id + CultureDelimiter + poFileName)))); // \src\OrchardCore.Cms.Web\App_Data/Localization/fr-CA/OrchardCore.Cms.Web.po yield return(new PhysicalFileInfo(new FileInfo(PathExtensions.Combine(_applicationDataContainer, _resourcesContainer, cultureName, extension.Id + PoFileExtension)))); } }
/// <summary> /// Entry point called from Doorstop /// </summary> /// <param name="args">First argument is the path of the currently executing process.</param> public static void Main(string[] args) { _paths = Paths.Create(); _logger = new Logger(PathExtensions.Combine(_paths.LogsPath, "PatchLoader.log")); _paths.WorkshopModsPath = GetWorkshopModsPath(_paths.WorkingPath, _logger); _logger.Info("Detected paths:\n" + _paths); if (_paths.DisableMods) { _logger.Info("******** Mods loading disabled via --disableMods commandline argument. Further execution aborted ********"); return; } if (_paths.SkipWorkshop) { _logger.Info("******** Workshop mods loading disabled via --noWorkshop commandline argument. Processing workshop mods directories will be skipped ********"); } try { AppDomain.CurrentDomain.TypeResolve += AssemblyResolver; AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolver; new InternalLoader(_logger, _paths) .Run(); } catch (Exception e) { _logger.Exception(e); } finally { AppDomain.CurrentDomain.AssemblyResolve -= AssemblyResolver; AppDomain.CurrentDomain.TypeResolve -= AssemblyResolver; } }
/// <inheritdocs /> public IEnumerable <IFileInfo> GetLocations(string cultureName) { var poFileName = cultureName + PoFileExtension; var extensions = _extensionsManager.GetExtensions(); // Load .po files in each extension folder first, based on the extensions order foreach (var extension in extensions) { // From [Extension]/Localization yield return(_fileProvider.GetFileInfo(PathExtensions.Combine(extension.SubPath, _resourcesContainer, poFileName))); } // Load global .po files from /Localization yield return(_fileProvider.GetFileInfo(PathExtensions.Combine(_resourcesContainer, poFileName))); // Load tenant-specific .po file from /App_Data/Sites/[Tenant]/Localization yield return(new PhysicalFileInfo(new FileInfo(PathExtensions.Combine(_shellDataContainer, _resourcesContainer, poFileName)))); // Load each modules .po file for extending localization when using Orchard Core as a NuGet package foreach (var extension in extensions) { // \src\OrchardCore.Cms.Web\Localization\OrchardCore.Cms.Web\fr-CA.po yield return(_fileProvider.GetFileInfo(PathExtensions.Combine(_resourcesContainer, extension.Id, poFileName))); // \src\OrchardCore.Cms.Web\Localization\OrchardCore.Cms.Web-fr-CA.po yield return(_fileProvider.GetFileInfo(PathExtensions.Combine(_resourcesContainer, extension.Id + CultureDelimiter + poFileName))); } // Load all .po files from a culture specific folder // e.g, \src\OrchardCore.Cms.Web\Localization\fr-CA\*.po foreach (var file in _fileProvider.GetDirectoryContents(PathExtensions.Combine(_resourcesContainer, cultureName))) { yield return(file); } }
private Func <FileEntryDto, Task> UploadConcurrentFilesAsync( string localPath, string storagePath, SemaphoreSlim semaphore, IProgress <StorageProgressDto> progress, CancellationToken cancellationToken) { return(async directory => { await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { var data = File.ReadAllBytes(PathExtensions.Combine(localPath, directory.Path, "\\")); var fileName = directory.Path.PopLast(); var fullStoragePath = PathExtensions.Combine(storagePath, directory.Path, "/"); await _storageProvider .UploadFileAsync(data, fullStoragePath, fileName, progress, cancellationToken) .ConfigureAwait(false); } finally { semaphore.Release(); } }); }
public async Task <IActionResult> Import(IFormFile importedPackage) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.Import)) { return(Forbid()); } if (importedPackage != null) { var tempArchiveName = Path.GetTempFileName() + Path.GetExtension(importedPackage.FileName); var tempArchiveFolder = PathExtensions.Combine(Path.GetTempPath(), Path.GetRandomFileName()); try { using (var stream = new FileStream(tempArchiveName, FileMode.Create)) { await importedPackage.CopyToAsync(stream); } if (importedPackage.FileName.EndsWith(".zip")) { ZipFile.ExtractToDirectory(tempArchiveName, tempArchiveFolder); } else if (importedPackage.FileName.EndsWith(".json")) { Directory.CreateDirectory(tempArchiveFolder); System.IO.File.Move(tempArchiveName, Path.Combine(tempArchiveFolder, "Recipe.json")); } else { await _notifier.ErrorAsync(H["Only zip or json files are supported."]); return(RedirectToAction(nameof(Index))); } await _deploymentManager.ImportDeploymentPackageAsync(new PhysicalFileProvider(tempArchiveFolder)); await _notifier.SuccessAsync(H["Deployment package imported."]); } finally { if (System.IO.File.Exists(tempArchiveName)) { System.IO.File.Delete(tempArchiveName); } if (Directory.Exists(tempArchiveFolder)) { Directory.Delete(tempArchiveFolder, true); } } } else { await _notifier.ErrorAsync(H["Please add a file to import."]); } return(RedirectToAction(nameof(Index))); }
public bool Exists(string indexName) { if (String.IsNullOrWhiteSpace(indexName)) { return(false); } return(Directory.Exists(PathExtensions.Combine(_rootPath, indexName))); }
public override void ConfigureServices(IServiceCollection services) { // services.AddSession(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); // transformalize services services.AddScoped(sp => new MemoryLogger(LogLevel.Info)); services.AddScoped(typeof(CombinedLogger <>)); services.AddScoped <ILinkService, LinkService>(); services.AddScoped <ISortService, SortService>(); services.AddScoped <IArrangementService, ArrangementService>(); services.AddScoped <IArrangementLoadService, ArrangementLoadService>(); services.AddScoped <IArrangementRunService, ArrangementRunService>(); services.AddScoped <IArrangementSchemaService, ArrangementSchemaService>(); services.AddScoped <IParameterService, ParameterService>(); services.AddScoped <ICommonService, CommonService>(); services.AddScoped <IReportService, ReportService>(); services.AddScoped <ITaskService, TaskService>(); services.AddScoped <IFormService, FormService>(); services.AddScoped <ISchemaService, SchemaService>(); services.AddScoped <ISettingsService, SettingsService>(); services.AddScoped <ITransformalizeParametersModifier, TransformalizeParametersModifier>(); services.AddScoped <ILoadFormModifier, LoadFormModifier>(); services.AddScoped <IFileService, FileService>(); services.AddTransient <IConfigurationContainer, OrchardConfigurationContainer>(); services.AddTransient <IContainer, OrchardContainer>(); // orchard cms services services.AddScoped <IDataMigration, Migrations>(); services.AddScoped <IPermissionProvider, Permissions>(); services.AddScoped <IResourceManifestProvider, ResourceManifest>(); services.AddScoped <IContentHandler, TransformalizeHandler>(); // parts services.AddContentPart <TransformalizeReportPart>().UseDisplayDriver <TransformalizeReportPartDisplayDriver>(); services.AddContentPart <TransformalizeTaskPart>().UseDisplayDriver <TransformalizeTaskPartDisplayDriver>(); services.AddContentPart <TransformalizeFormPart>().UseDisplayDriver <TransformalizeFormPartDisplayDriver>(); services.AddContentPart <TransformalizeFilePart>().UseDisplayDriver <TransformalizeFilePartDisplayDriver>(); // settings services.AddScoped <IDisplayDriver <ISite>, TransformalizeSettingsDisplayDriver>(); services.AddScoped <INavigationProvider, TransformalizeSettingsAdminMenu>(); // activities services.AddActivity <TransformalizeActivity, TransformalizeActivityDisplayDriver>(); // file system, see https://github.com/Lombiq/Orchard-Training-Demo-Module/blob/dev/Startup.cs services.AddSingleton <ICustomFileStore>(serviceProvider => { var options = serviceProvider.GetRequiredService <IOptions <ShellOptions> >().Value; var settings = serviceProvider.GetRequiredService <ShellSettings>(); var sitePath = PathExtensions.Combine(options.ShellsApplicationDataPath, options.ShellsContainerName, settings.Name); var path = PathExtensions.Combine(sitePath, "Transformalize", "Files"); return(new CustomFileStore(path)); }); }
private IndexReaderPool.IndexReaderLease GetReader(string indexName) { var pool = _indexPools.GetOrAdd(indexName, n => { var path = new DirectoryInfo(PathExtensions.Combine(_rootPath, indexName)); var reader = DirectoryReader.Open(FSDirectory.Open(path)); return(new IndexReaderPool(reader)); }); return(pool.Acquire()); }
/// <summary> /// Creates a new intance of the <see cref="ModularPoFileLocationProvider"/>. /// </summary> /// <param name="extensionsManager">The <see cref="IExtensionManager"/>.</param> /// <param name="hostingEnvironment">The <see cref="IHostEnvironment"/>.</param> /// <param name="shellOptions">The <see cref="IOptions"/> for the <see cref="ShellOptions"/>.</param> /// <param name="localizationOptions">The <see cref="IOptions"/> for the <see cref="LocalizationOptions"/>.</param> /// <param name="shellSettings">The <see cref="ShellSettings"/>.</param> public ModularPoFileLocationProvider( IExtensionManager extensionsManager, IHostEnvironment hostingEnvironment, IOptions <ShellOptions> shellOptions, IOptions <LocalizationOptions> localizationOptions, ShellSettings shellSettings) { _extensionsManager = extensionsManager; _fileProvider = hostingEnvironment.ContentRootFileProvider; _resourcesContainer = localizationOptions.Value.ResourcesPath; _applicationDataContainer = shellOptions.Value.ShellsApplicationDataPath; _shellDataContainer = PathExtensions.Combine(_applicationDataContainer, shellOptions.Value.ShellsContainerName, shellSettings.Name); }
public override void ConfigureServices(IServiceCollection services) { services.AddScoped <IDataMigration, Migrations>(); services.AddScoped <IResourceManifestProvider, ResourceManifest>(); services.AddScoped <INavigationProvider, AdminMenu>(); services.AddScoped <IPermissionProvider, Permissions>(); //comment part // services.AddScoped<IContentPartDisplayDriver, CommentPartDisplayDriver>(); services.AddContentPart <CommentPart>().UseDisplayDriver <CommentPartDisplayDriver>() .AddHandler <CommentPartHandler>(); // services.AddScoped<IContentPartHandler, CommentPartHandler>(); services.AddScoped <IContentHandler, ContentItemCommentsHandler>(); //services // services.AddScoped<ICommentRepository, CommentRepository>(); // services.AddScoped<ICommentUserVoteRepository, CommentUserVoteRepository>(); services.AddScoped <ICommentRepositoryDapper, CommentRepositoryDapper>(); services.AddScoped <ICommentUserVoteRepositoryDapper, CommentUserVoteRepositoryDapper>(); // File System services.AddSingleton <ICommentsFileStore>(serviceProvider => { // So our goal here is to have a custom folder in the tenant's own folder. The Media folder is also // there but we won't use that. To get tenant-specific data we need to use the ShellOptions and // ShellShettings objects. var shellOptions = serviceProvider.GetRequiredService <IOptions <ShellOptions> >().Value; var shellSettings = serviceProvider.GetRequiredService <ShellSettings>(); var tenantFolderPath = PathExtensions.Combine( // This is the absolute path of the "App_Data" folder. shellOptions.ShellsApplicationDataPath, // This is the folder which contains the tenants which is Sites by default. shellOptions.ShellsContainerName, // This is the tenant name. We want our custom folder inside this folder. shellSettings.Name); // And finally our full base path. var customFolderPath = PathExtensions.Combine(tenantFolderPath, "CommentAttachments"); // Now register our CustomFileStore instance with the path given. return(new CommentAttachmentsFileStore(customFolderPath)); // NEXT STATION: Controllers/FileManagementController and find the CreateFileInCustomFolder method. }); }
public static Paths Create() { var workingPath = ""; bool isMac = Environment.GetEnvironmentVariable("DOORSTOP_MANAGED_FOLDER_DIR").Contains("Cities.app"); if (isMac) { workingPath = new DirectoryInfo(Environment.GetEnvironmentVariable("DOORSTOP_MANAGED_FOLDER_DIR")).Parent?.Parent?.Parent?.FullName; } else { workingPath = new DirectoryInfo(Environment.GetEnvironmentVariable("DOORSTOP_MANAGED_FOLDER_DIR")).Parent?.Parent?.FullName; } var loaderPath = Path.GetDirectoryName(Environment.GetEnvironmentVariable("DOORSTOP_INVOKE_DLL_PATH")); var managedFolderPath = Environment.GetEnvironmentVariable("DOORSTOP_MANAGED_FOLDER_DIR"); var filesModsPath = ""; if (isMac) { filesModsPath = PathExtensions.Combine(workingPath, "Resources", "Files", "Mods"); } else { filesModsPath = PathExtensions.Combine(workingPath, "Files", "Mods"); } var appDataPath = ""; if (isMac) { appDataPath = PathExtensions.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Library"), "Application Support", "Colossal Order", "Cities_Skylines"); } else { appDataPath = PathExtensions.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Colossal Order", "Cities_Skylines"); } var appDataModsPath = PathExtensions.Combine(appDataPath, "Addons", "Mods"); return(new Paths( workingPath, loaderPath, managedFolderPath, filesModsPath, appDataPath, appDataModsPath)); }
public static Paths Create() { var workingPath = new DirectoryInfo(Environment.GetEnvironmentVariable("DOORSTOP_MANAGED_FOLDER_DIR")).Parent.Parent.FullName; var loaderPath = Path.GetDirectoryName(Environment.GetEnvironmentVariable("DOORSTOP_INVOKE_DLL_PATH")); var managedFolderPath = Environment.GetEnvironmentVariable("DOORSTOP_MANAGED_FOLDER_DIR"); var filesModsPath = PathExtensions.Combine(workingPath, "Files", "Mods"); var appDataModsPath = PathExtensions.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Colossal Order", "Cities_Skylines", "Addons", "Mods"); return(new Paths( workingPath, loaderPath, managedFolderPath, filesModsPath, appDataModsPath)); }
public async Task <IActionResult> Execute(int id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.Export)) { return(Forbid()); } var deploymentPlan = await _session.GetAsync <DeploymentPlan>(id); if (deploymentPlan == null) { return(NotFound()); } string archiveFileName; var filename = deploymentPlan.Name.ToSafeName() + ".zip"; using (var fileBuilder = new TemporaryFileBuilder()) { archiveFileName = PathExtensions.Combine(Path.GetTempPath(), filename); var recipeDescriptor = new RecipeDescriptor(); var recipeFileDeploymentStep = deploymentPlan.DeploymentSteps.FirstOrDefault(ds => ds.Name == nameof(RecipeFileDeploymentStep)) as RecipeFileDeploymentStep; if (recipeFileDeploymentStep != null) { recipeDescriptor.Name = recipeFileDeploymentStep.RecipeName; recipeDescriptor.DisplayName = recipeFileDeploymentStep.DisplayName; recipeDescriptor.Description = recipeFileDeploymentStep.Description; recipeDescriptor.Author = recipeFileDeploymentStep.Author; recipeDescriptor.WebSite = recipeFileDeploymentStep.WebSite; recipeDescriptor.Version = recipeFileDeploymentStep.Version; recipeDescriptor.IsSetupRecipe = recipeFileDeploymentStep.IsSetupRecipe; recipeDescriptor.Categories = (recipeFileDeploymentStep.Categories ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries); recipeDescriptor.Tags = (recipeFileDeploymentStep.Tags ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries); } var deploymentPlanResult = new DeploymentPlanResult(fileBuilder, recipeDescriptor); await _deploymentManager.ExecuteDeploymentPlanAsync(deploymentPlan, deploymentPlanResult); ZipFile.CreateFromDirectory(fileBuilder.Folder, archiveFileName); } return(new PhysicalFileResult(archiveFileName, "application/zip") { FileDownloadName = filename }); }
public async Task SetFileAsync(string subpath, Stream stream) { var fullname = PathExtensions.Combine(Folder, subpath); var directory = new FileInfo(fullname).Directory; if (!directory.Exists) { directory.Create(); } using (var fs = File.Create(fullname, 4 * 1024, FileOptions.None)) { await stream.CopyToAsync(fs); } }
public IEnumerable <IFileInfo> GetLocations(string cultureName) { var poFileName = cultureName + PoFileExtension; // Load .po files in each extension folder first, based on the extensions order foreach (var extension in _extensionsManager.GetExtensions()) { yield return(_fileProvider.GetFileInfo(PathExtensions.Combine(extension.SubPath, ExtensionDataFolder, _resourcesContainer, poFileName))); } // Then load global .po file for the applications yield return(new PhysicalFileInfo(new FileInfo(PathExtensions.Combine(_applicationDataContainer, _resourcesContainer, poFileName)))); // Finally load tenant-specific .po file yield return(new PhysicalFileInfo(new FileInfo(PathExtensions.Combine(_shellDataContainer, _resourcesContainer, poFileName)))); }
public void OnEnabled() { _pluginInfo = PluginManager.instance.FindPluginInfo(Assembly.GetExecutingAssembly()); EnsureLogsDirectoryCreated(); _logger = new Utils.Logger(Path.Combine(Path.Combine(Application.dataPath, "Logs"), "PatchLoaderMod.log")); _patchLoaderConfigFilePath = Path.Combine(DataLocation.applicationBase, "PatchLoader.Config.xml"); _configManager = new ConfigManager <Config>(_patchLoaderConfigFilePath, _logger); var expectedTargetAssemblyPath = PathExtensions.Combine( _pluginInfo.modPath, "PatchLoader", "PatchLoader.dll" ); _doorstopManager = DoorstopManager.Create(expectedTargetAssemblyPath, _logger); if (Application.platform == RuntimePlatform.OSXPlayer) { ShowExceptionModal($"The '{Name}'\nMacOS platform is not supported yet.\n\n" + "Mod will disable itself.\n" + "Follow FPS Booster and PatchLoader mod development to stay informed about changes.\n" + "MacOS support will be added in one of the next major updates for PatchLoader mod.", () => { _pluginInfo.isEnabled = false; }); return; } if (!_doorstopManager.IsInstalled()) { _doorstopManager.Install(); SaveOrUpdateWorkshopPath(); } if (_doorstopManager.CanEnable && !_doorstopManager.IsEnabled()) { _doorstopManager.Enable(); } if (_doorstopManager.RequiresRestart) { ShowRestartGameModal($"The '{Name}' was installed.\n{_doorstopManager.InstallMessage}"); } Debug.Log("PatchLoader enabled"); }
public async Task CreateDirectoriesAsync( string path, IList <FileEntryDto> directories, IProgress <StorageProgressDto> progress, CancellationToken cancellationToken) { await Task.Run(() => Parallel.ForEach(directories, directory => { var fullLocalPath = PathExtensions.Combine(path, directory.Path, "\\"); progress.ReportCreateDirectory(fullLocalPath); Directory.CreateDirectory(fullLocalPath); }), cancellationToken) .ConfigureAwait(false); }
public async Task <IActionResult> Import(ImportViewModel model) { var remoteClientList = await _remoteClientService.GetRemoteClientListAsync(); var remoteClient = remoteClientList.RemoteClients.FirstOrDefault(x => x.ClientName == model.ClientName); var apiKey = Encoding.UTF8.GetString(_dataProtector.Unprotect(remoteClient.ProtectedApiKey)); if (remoteClient == null || model.ApiKey != apiKey || model.ClientName != remoteClient.ClientName) { return(StatusCode((int)HttpStatusCode.BadRequest, "The Api Key was not recognized")); } // Create a temporary filename to save the archive var tempArchiveName = Path.GetTempFileName() + ".zip"; // Create a temporary folder to extract the archive to var tempArchiveFolder = PathExtensions.Combine(Path.GetTempPath(), Path.GetRandomFileName()); try { using (var fs = System.IO.File.Create(tempArchiveName)) { await model.Content.CopyToAsync(fs); } ZipFile.ExtractToDirectory(tempArchiveName, tempArchiveFolder); await _deploymentManager.ImportDeploymentPackageAsync(new PhysicalFileProvider(tempArchiveFolder)); } finally { if (System.IO.File.Exists(tempArchiveName)) { System.IO.File.Delete(tempArchiveName); } if (Directory.Exists(tempArchiveFolder)) { Directory.Delete(tempArchiveFolder, true); } } return(Ok()); }
public LuceneIndexManager( IClock clock, IOptions <ShellOptions> shellOptions, ShellSettings shellSettings, ILogger <LuceneIndexManager> logger, LuceneAnalyzerManager luceneAnalyzerManager ) { _clock = clock; _logger = logger; _rootPath = PathExtensions.Combine( shellOptions.Value.ShellsApplicationDataPath, shellOptions.Value.ShellsContainerName, shellSettings.Name, "Lucene"); _rootDirectory = Directory.CreateDirectory(_rootPath); _luceneAnalyzerManager = luceneAnalyzerManager; }
private BaseDirectory CreateDirectory(string indexName) { lock (this) { var path = new DirectoryInfo(PathExtensions.Combine(_rootPath, indexName)); if (!path.Exists) { path.Create(); } // Lucene is not thread safe on this call lock (_synLock) { return(FSDirectory.Open(path)); } } }
public async Task UploadFileAsync( string localPath, string storagePath, IProgress <StorageProgressDto> progress, CancellationToken cancellationToken) { var data = File.ReadAllBytes(localPath); var pathInParts = PathExtensions.GetPathInParts(storagePath, '/'); var fileName = pathInParts.PopLast(); var fullStoragePath = PathExtensions.Combine(string.Empty, pathInParts, "/"); await _storageProvider.UploadDirectoriesAsync(pathInParts.PopFirst(), new FileEntryDto(pathInParts), progress, cancellationToken).ConfigureAwait(false); await _storageProvider .UploadFileAsync(data, fullStoragePath, fileName, progress, cancellationToken) .ConfigureAwait(false); }
public async Task CreateFileAsync( string localPath, string storagePath, IProgress <StorageProgressDto> progress, CancellationToken cancellationToken) { var pathInParts = PathExtensions.GetPathInParts(storagePath, '/'); var fileName = pathInParts.PopLast(); var data = await _storageProvider.DownloadFileAsync(PathExtensions.Combine(string.Empty, pathInParts, "/"), fileName, progress, cancellationToken) .ConfigureAwait(false); using (var fileStream = File.Open($"{localPath.TrimEnd('\\')}\\{fileName}", FileMode.Create)) { cancellationToken.ThrowIfCancellationRequested(); progress.ReportSaveFile(localPath, data.Length); await fileStream.WriteAsync(data, 0, data.Length, cancellationToken).ConfigureAwait(false); } }
private async Task <string> CopyFileToCacheFolder(IServiceProvider serviceProvider, ContentItem contentItem, string mapImagePath) { _logger.LogInformation($"Copying file from media library to local file system"); var mediaStore = serviceProvider.GetRequiredService <IMediaFileStore>(); var path = PathExtensions.Combine(CacheDirectory, contentItem.ContentItemId); var fileStream = await mediaStore.GetFileStreamAsync(mapImagePath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var tempFile = File.Create(Path.Combine(path, Path.GetFileName(mapImagePath))); fileStream.CopyTo(tempFile); tempFile.Close(); return(Path.Combine(path, Path.GetFileName(mapImagePath))); }
public ElasticIndexingState( IOptions <ShellOptions> shellOptions, ShellSettings shellSettings ) { _indexSettingsFilename = PathExtensions.Combine( shellOptions.Value.ShellsApplicationDataPath, shellOptions.Value.ShellsContainerName, shellSettings.Name, "lucene.status.json"); if (!File.Exists(_indexSettingsFilename)) { Directory.CreateDirectory(Path.GetDirectoryName(_indexSettingsFilename)); File.WriteAllText(_indexSettingsFilename, new JObject().ToString(Newtonsoft.Json.Formatting.Indented)); } _content = JObject.Parse(File.ReadAllText(_indexSettingsFilename)); }