public override void Configure(Container container) { SetConfig(new HostConfig { DebugMode = true, }); var contentRoot = Path.GetFullPath("../../../../ProtocApi"); var protocPath = Path.Combine(contentRoot, "protoc"); var exeDirPath = Env.IsWindows ? Path.Combine(protocPath, "win64") : Path.Combine(protocPath, "linux64"); var protocConfig = new ProtocConfig { ExePath = Env.IsWindows ? Path.Combine(exeDirPath, "protoc.exe") : Path.Combine(exeDirPath, "protoc"), PluginPath = exeDirPath, ProtoIncludeDirectory = Path.Combine(protocPath, "include"), TempDirectory = Path.Combine(contentRoot, "tmp"), }; try { FileSystemVirtualFiles.DeleteDirectoryRecursive(protocConfig.TempDirectory); } catch {} try { Directory.CreateDirectory(protocConfig.TempDirectory); } catch {} container.Register(protocConfig); }
public async Task PrerenderMarkdown() { var srcDir = WwrootDir.CombineWith("content").Replace('\\', '/'); var dstDir = WwrootDir.CombineWith("docs").Replace('\\', '/'); var indexPage = PageTemplate.Create(WwrootDir.CombineWith("index.html")); if (!Directory.Exists(srcDir)) { throw new Exception($"{Path.GetFullPath(srcDir)} does not exist"); } FileSystemVirtualFiles.RecreateDirectory(dstDir); foreach (var file in new DirectoryInfo(srcDir).GetFiles("*.md", SearchOption.AllDirectories)) { WriteLine($"Converting {file.FullName} ..."); var name = file.Name.WithoutExtension(); var docRender = await Client.MarkdownUtils.LoadDocumentAsync(name, doc => Task.FromResult(File.ReadAllText(file.FullName))); if (docRender.Failed) { WriteLine($"Failed: {docRender.ErrorMessage}"); continue; } var dirName = dstDir.IndexOf("wwwroot") >= 0 ? dstDir.LastRightPart("wwwroot").Replace('\\', '/') : new DirectoryInfo(dstDir).Name; var path = dirName.CombineWith(name == "index" ? "" : name); var mdBody = @$ " <div class=" "prose lg:prose-xl min-vh-100 m-3" " data-prerender=" "{path}" ">
public override void Configure(Container container) { SharedAppHostConfig.Configure(this, "~/App_Data/packages".MapHostAbsolutePath()); VirtualFiles = new FileSystemVirtualFiles(MapProjectPath("~/")); Config.WebHostPhysicalPath = MapProjectPath("~/wwwroot"); Config.DebugMode = true; }
public PrerenderTasks() { Context = new(); var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); ClientDir = config[nameof(ClientDir)] ?? throw new Exception($"{nameof(ClientDir)} not defined in appsettings.json"); FileSystemVirtualFiles.RecreateDirectory(PrerenderDir); }
public void Update_Razor_and_Markdown_pages_at_runtime() { var fs = new FileSystemVirtualFiles("~/../RazorRockstars.WebHost".MapHostAbsolutePath()); var kurtRazor = fs.GetFile("stars/dead/cobain/default.cshtml"); s3.WriteFile(kurtRazor.VirtualPath, "[UPDATED RAZOR] " + kurtRazor.ReadAllText()); var kurtMarkdown = fs.GetFile("stars/dead/cobain/Content.md"); s3.WriteFile(kurtMarkdown.VirtualPath, "[UPDATED MARKDOWN] " + kurtMarkdown.ReadAllText()); }
public override void OnConfigLoad() { if (app != null) { //Initialize VFS var env = app.ApplicationServices.GetService <IHostingEnvironment>(); Config.WebHostPhysicalPath = env.ContentRootPath; //Set VirtualFiles to point to ContentRootPath (Project Folder) VirtualFiles = new FileSystemVirtualFiles(env.ContentRootPath); RegisterLicenseFromAppSettings(AppSettings); } }
public void 新增檔案() { var executingAssembly = Assembly.GetExecutingAssembly(); var rootPath = Path.GetDirectoryName(executingAssembly.Location); var subPath = "TestFolder"; var content = "This is test string"; var virtualFiles = new FileSystemVirtualFiles(rootPath); if (virtualFiles.DirectoryExists(subPath) == false) { virtualFiles.EnsureDirectory(subPath); } virtualFiles.AppendFile($"{subPath}/1.txt", content); }
public override void OnConfigLoad() { base.OnConfigLoad(); if (app != null) { //Initialize VFS var env = app.ApplicationServices.GetService <IHostingEnvironment>(); Config.WebHostPhysicalPath = env.WebRootPath ?? env.ContentRootPath; Config.DebugMode = env.IsDevelopment(); //Set VirtualFiles to point to ContentRootPath (Project Folder) VirtualFiles = new FileSystemVirtualFiles(env.ContentRootPath); AppHostBase.RegisterLicenseFromAppSettings(AppSettings); Config.MetadataRedirectPath = "metadata"; } }
public override void OnConfigLoad() { base.OnConfigLoad(); if (app != null) { //Initialize VFS Config.WebHostPhysicalPath = HostingEnvironment.ContentRootPath; Config.DebugMode = HostingEnvironment.IsDevelopment(); if (VirtualFiles == null) { //Set VirtualFiles to point to ContentRootPath (Project Folder) VirtualFiles = new FileSystemVirtualFiles(HostingEnvironment.ContentRootPath); } RegisterLicenseFromAppSettings(AppSettings); } }
public override void OnConfigLoad() { base.OnConfigLoad(); if (app != null) { //Initialize VFS Config.WebHostPhysicalPath = HostingEnvironment.ContentRootPath; Config.DebugMode = HostingEnvironment.IsDevelopment(); Config.HandlerFactoryPath = Environment.GetEnvironmentVariable($"ASPNETCORE_APPL_PATH"); //IIS Mapping / sometimes UPPER CASE https://serverfault.com/q/292335 if (VirtualFiles == null) { //Set VirtualFiles to point to ContentRootPath (Project Folder) VirtualFiles = new FileSystemVirtualFiles(HostingEnvironment.ContentRootPath); } RegisterLicenseFromAppSettings(AppSettings); } }
public void 新增資料夾() { var executingAssembly = Assembly.GetExecutingAssembly(); var rootPath = Path.GetDirectoryName(executingAssembly.Location); var content = "This is test string"; var subPath = "TestFolder"; var subPath1 = $"{subPath}/1/1_1/1_1_1"; var subPath2 = $"{subPath}/2"; var fileSystem = new FileSystemVirtualFiles(rootPath); fileSystem.EnsureDirectory(subPath1); fileSystem.EnsureDirectory(subPath2); fileSystem.AppendFile($"{subPath}/1.txt", content); var memoryFileSystem = new MemoryVirtualFiles(); // var memoryFileSystem1 = fileSystem.GetMemoryVirtualFiles(); // var nonDefaultValues = fileSystem.PopulateWithNonDefaultValues(memoryFileSystem); // var memoryFileSystem2 = memoryFileSystem.PopulateWith(fileSystem); var subFolder = new InMemoryVirtualDirectory(memoryFileSystem, subPath); var subFile = new InMemoryVirtualFile(memoryFileSystem, subFolder); memoryFileSystem.AddFile(subFile); //無法單獨加入資料夾 var subFolder1 = new InMemoryVirtualDirectory(memoryFileSystem, "1", subFolder); var subFolder2 = new InMemoryVirtualDirectory(memoryFileSystem, "1_1", subFolder1); subFolder2.AddFile("2.txt", content); var directories = memoryFileSystem.RootDirectory.Directories; var files = memoryFileSystem.Files; Console.WriteLine(); // // // memorySystem.AddFile(new InMemoryVirtualFile(fileSystem, directory)); // // // memorySystem.AppendFile($"{subPath1}/1.txt",content); // var files = memoryFileSystem.GetAllFiles(); }
public async Task Put(DesktopFile request) { AssertFile(request.File); var appSettingsDir = GetDesktopFilesDirectory(); FileSystemVirtualFiles.AssertDirectory(appSettingsDir); var filePath = Path.Combine(appSettingsDir, request.File); var tmpFilePath = Path.Combine(appSettingsDir, request.File + ".tmp"); try { File.Delete(tmpFilePath); } catch {} using (var fs = new FileInfo(tmpFilePath).Open(FileMode.OpenOrCreate)) { await request.RequestStream.CopyToAsync(fs); } try { File.Delete(filePath); } catch {} File.Move(tmpFilePath, filePath); }
public void 新增資料夾() { var executingAssembly = Assembly.GetExecutingAssembly(); var rootPath = Path.GetDirectoryName(executingAssembly.Location); var subPath = "TestFolder"; var subPath1 = $"{subPath}/1/1_1/1_1_1"; var subPath2 = $"{subPath}/2"; var virtualFiles = new FileSystemVirtualFiles(rootPath); if (virtualFiles.DirectoryExists(subPath1) == false) { virtualFiles.EnsureDirectory(subPath1); } if (virtualFiles.DirectoryExists(subPath2) == false) { virtualFiles.EnsureDirectory(subPath2); } virtualFiles.DeleteFolder(subPath); }
public static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: "); Console.WriteLine("copy-files [provider] [config]"); Console.WriteLine("\nVirtual File System Providers:"); Console.WriteLine(" - files [destination]"); Console.WriteLine(" - s3 {AccessKey:key,SecretKey:secretKey,Region:us-east-1,Bucket:s3Bucket}"); Console.WriteLine(" - azure {ConnectionString:connectionString,ContainerName:containerName}"); return; } var destFs = GetVirtualFiles(ResolveValue(args[0]), ResolveValue(args[1])); if (destFs == null) { Console.WriteLine("Unknown Provider: " + ResolveValue(args[0])); return; } var sourcePath = SourcePath.MapProjectPath(); if (!Directory.Exists(sourcePath)) { Console.WriteLine("Source Directory does not exist: " + sourcePath); return; } var sourceFs = new FileSystemVirtualFiles(sourcePath); foreach (var file in sourceFs.GetAllMatchingFiles("*")) { Console.WriteLine("Copying: " + file.VirtualPath); destFs.WriteFile(file); } }
public void Copy_Razor_files_to_AWS_Bucket() { var fs = new FileSystemVirtualFiles("~/../RazorRockstars.WebHost".MapHostAbsolutePath()); var skipDirs = new[] { "bin", "obj" }; var matchingFileTypes = new[] { "cshtml", "md", "css", "js", "png", "jpg" }; var replaceHtmlTokens = new Dictionary <string, string> { { "title-bg.png", "title-bg-aws.png" }, //Title Background { "https://gist.github.com/3617557.js", "https://gist.github.com/mythz/396dbf54ce6079cc8b2d.js" }, //AppHost.cs { "https://gist.github.com/3616766.js", "https://gist.github.com/mythz/ca524426715191b8059d.js" }, //S3 RockstarsService.cs { "RazorRockstars.WebHost/RockstarsService.cs", "RazorRockstars.S3/RockstarsService.cs" }, //S3 RockstarsService.cs { "http://github.com/ServiceStackApps/RazorRockstars/", "https://github.com/ServiceStackApps/RazorRockstars/tree/master/src/RazorRockstars.S3" } //Link to GitHub project }; foreach (var file in fs.GetAllFiles()) { if (skipDirs.Any(x => file.VirtualPath.StartsWith(x))) { continue; } if (!matchingFileTypes.Contains(file.Extension)) { continue; } if (file.Extension == "cshtml") { var html = file.ReadAllText(); replaceHtmlTokens.Each(x => html = html.Replace(x.Key, x.Value)); s3.WriteFile(file.VirtualPath, html); } else { s3.WriteFile(file); } } }
public async Task Create_TypeScript_Definitions_Publish() { Directory.SetCurrentDirectory(NetCoreTestsDir); await ProcessUtils.RunShellAsync("rd /q /s types && tsc", onOut : Console.WriteLine, onError : Console.Error.WriteLine); // Export API Explorer's .d.ts to 'explorer' Directory.Move("types/ui", "types/explorer"); Directory.Move("types/admin-ui", "types/admin"); FileSystemVirtualFiles.RecreateDirectory("dist"); File.Copy("../NorthwindAuto/node_modules/@servicestack/client/dist/index.d.ts", "dist/client.d.ts"); File.Copy("../NorthwindAuto/node_modules/@servicestack/client/dist/index.d.ts", "../NorthwindAuto/lib/client.d.ts", overwrite: true); var memFs = new MemoryVirtualFiles(); var typesFs = new FileSystemVirtualFiles("types"); var distFs = new FileSystemVirtualFiles("dist"); var typesFile = typesFs.GetFile("lib/types.d.ts"); memFs.WriteFile("0_" + typesFile.Name, typesFile); memFs.TransformAndCopy("shared", typesFs, distFs); memFs.Clear(); memFs.TransformAndCopy("locode", typesFs, distFs); memFs.Clear(); memFs.TransformAndCopy("explorer", typesFs, distFs); memFs.Clear(); memFs.TransformAndCopy("admin", typesFs, distFs); var libFs = new FileSystemVirtualFiles("../../../../servicestack-ui".AssertDir()); libFs.CopyFrom(distFs.GetAllFiles()); }
// Configure your AppHost with the necessary configuration and dependencies your App needs public override void Configure(Container container) { // JsConfig.Init(new ServiceStack.Text.Config { // IncludeNullValues = true, // TextCase = TextCase.PascalCase // }); SetConfig(new HostConfig { //DebugMode = false, DebugMode = true, AdminAuthSecret = "secret", }); var memFs = GetVirtualFileSource <MemoryVirtualFiles>(); var files = VirtualFiles.GetDirectory("custom").GetAllFiles(); files.Each(file => memFs.WriteFile($"locode/{file.Name}", file)); GlobalRequestFilters.Add((req, res, dto) => { files.Each(file => memFs.WriteFile($"locode/{file.Name}", file)); }); ConfigurePlugin <UiFeature>(feature => { Console.WriteLine(@"ConfigurePlugin<UiFeature>..."); feature.HtmlModules.Add(new("/modules/forms", "/forms")); feature.Module.Configure((appHost, module) => { module.VirtualFiles = appHost.VirtualFiles; module.DirPath = module.DirPath.Replace("/modules", ""); }); feature.Handlers.Cast <SharedFolder>().Each(x => x.SharedDir = x.SharedDir.Replace("/modules", "")); }); // Not needed in `dotnet watch` and in /wwwroot/modules/ui which can use _framework/aspnetcore-browser-refresh.js" Plugins.AddIfDebug(new HotReloadFeature { VirtualFiles = VirtualFiles, DefaultPattern = "*.html;*.js;*.css" }); //Plugins.Add(new PostmanFeature()); var uploadVfs = new FileSystemVirtualFiles(TalentBlazorWwwRootDir); var appDataVfs = new FileSystemVirtualFiles(TalentBlazorAppDataDir); Plugins.Add(new FilesUploadFeature( new UploadLocation("profiles", uploadVfs, allowExtensions: FileExt.WebImages, resolvePath: ctx => $"/profiles/{ctx.FileName}"), new UploadLocation("game_items", appDataVfs, allowExtensions: FileExt.WebImages), new UploadLocation("files", GetVirtualFileSource <FileSystemVirtualFiles>(), resolvePath: ctx => $"/files/{ctx.FileName}"), new UploadLocation("users", uploadVfs, allowExtensions: FileExt.WebImages, resolvePath: ctx => $"/profiles/users/{ctx.UserAuthId}.{ctx.FileExtension}"), new UploadLocation("applications", appDataVfs, maxFileCount: 3, maxFileBytes: 10_000_000, resolvePath: ctx => ctx.GetLocationPath((ctx.Dto is CreateJobApplication create ? $"job/{create.JobId}" : $"app/{ctx.Dto.GetId()}") + $"/{ctx.DateSegment}/{ctx.FileName}"), readAccessRole: RoleNames.AllowAnon, writeAccessRole: RoleNames.AllowAnon) )); Metadata.ForceInclude = new() { typeof(GetAccessToken) }; Plugins.Add(new ServiceStack.Api.OpenApi.OpenApiFeature()); }
public object Any(Protoc request) { var tmpId = (Request as IHasStringId)?.Id?.Replace("|", "").Replace(".", "") ?? Guid.NewGuid().ToString(); var files = request.Files ?? new Dictionary <string, string>(); if (!string.IsNullOrEmpty(request.ProtoUrl)) { var fileName = request.ProtoUrl.EndsWith(".proto") ? request.ProtoUrl.LastRightPart('/') : "services.proto"; files[fileName] = request.ProtoUrl.GetStringFromUrl(); } if (Request.Files.Length > 0) { foreach (var httpFile in Request.Files) { var fileName = httpFile.FileName ?? httpFile.Name; if (!fileName.EndsWith(".proto") && !fileName.EndsWith(".zip")) { throw new ArgumentException($"Unsupported file '{fileName}'. Only .proto or .zip files supported."); } if (fileName.EndsWith(".zip")) { var tmpZipPath = Path.GetTempFileName(); var tmpDir = Path.Combine(Path.GetTempPath(), "protoc-api", tmpId); httpFile.SaveTo(tmpZipPath); ZipFile.ExtractToDirectory(tmpZipPath, tmpDir); var tmpDirInfo = new DirectoryInfo(tmpDir); var hasProtoRootDir = tmpDirInfo.GetFiles("*.proto").Length > 0; var fsZipDir = !hasProtoRootDir && tmpDirInfo.GetDirectories().Length == 1 ? new FileSystemVirtualFiles(tmpDirInfo.GetDirectories()[0].FullName) : new FileSystemVirtualFiles(tmpDirInfo.FullName); foreach (var file in fsZipDir.GetAllFiles().Where(x => x.Extension == "proto")) { files[file.VirtualPath] = file.ReadAllText(); } } else { files[fileName] = httpFile.InputStream.ReadToEnd(); } } } if (files.IsEmpty()) { throw new ArgumentNullException(nameof(request.Files)); } var tmpPath = Path.Combine(ProtocConfig.TempDirectory, tmpId); var outPath = Path.Combine(tmpPath, "out"); try { Directory.CreateDirectory(outPath); } catch {} var fs = new FileSystemVirtualFiles(tmpPath); fs.WriteFiles(files); var langOptions = ProtocConfig.Languages[request.Lang]; var args = StringBuilderCache.Allocate(); var outArgs = ""; if (!langOptions.OutModifiers.IsEmpty()) { foreach (var modifier in langOptions.OutModifiers) { if (outArgs.Length > 0) { outArgs += ","; } outArgs += modifier; } if (outArgs.Length > 0) { outArgs += ":"; } } var grpcOut = ""; if (langOptions.GrpcOutModifiers != null) { grpcOut = " --grpc_out="; for (var i = 0; i < langOptions.GrpcOutModifiers.Length; i++) { if (i > 0) { grpcOut += ","; } var modifier = langOptions.GrpcOutModifiers[i]; grpcOut += modifier; } if (langOptions.GrpcOutModifiers.Length > 0) { grpcOut += ":"; } grpcOut += "out"; } args.AppendFormat($"-I . -I \"{ProtocConfig.ProtoIncludeDirectory}\" --{langOptions.Lang}_out={outArgs}out{grpcOut}"); if (!langOptions.GrpcWebModifiers.IsEmpty()) { var webArgs = ""; foreach (var modifier in langOptions.GrpcWebModifiers) { if (webArgs.Length > 0) { webArgs += ","; } webArgs += modifier; } if (webArgs.Length > 0) { webArgs += ":"; } args.AppendFormat($" --grpc-web_out={webArgs}out"); } if (!langOptions.Args.IsEmpty()) { foreach (var arg in langOptions.Args) { args.Append($" {arg}"); } } if (!langOptions.IndividuallyPerFile) { foreach (var entry in files) { args.Append($" {entry.Key}"); } exec(tmpPath, StringBuilderCache.ReturnAndFree(args)); } else { var argsBase = StringBuilderCache.ReturnAndFree(args); foreach (var entry in files) { exec(tmpPath, $"{argsBase} {entry.Key}"); } } var serviceName = files.Count == 1 ? files.Keys.First() : "grpc"; var archiveUrl = Request.ResolveAbsoluteUrl(new GetArchive { RequestId = tmpId, FileName = $"{serviceName}.{langOptions.Lang}.zip" }.ToGetUrl()); if (Request.QueryString["zip"] != null) { return(new HttpResult(new ProtocResponse { ArchiveUrl = archiveUrl }) { Location = archiveUrl }); } var response = new ProtocResponse { GeneratedFiles = new Dictionary <string, string>(), ArchiveUrl = archiveUrl, }; var fsOut = new FileSystemVirtualFiles(Path.Combine(tmpPath, "out")); var genFiles = fsOut.GetAllFiles(); foreach (var virtualFile in genFiles) { response.Lang = request.Lang; response.GeneratedFiles[virtualFile.VirtualPath] = virtualFile.GetTextContentsAsMemory().ToString(); } return(response); }
public FileSystemVirtualFileTest() { _virtualFiles = new FileSystemVirtualFiles(TestConfiguration.RootDirectory); }
private static void DeleteDirectory(string dir) { RetryExec(() => FileSystemVirtualFiles.DeleteDirectoryRecursive(dir)); }