public override Task <bool> InvokeAsync(string paramList) { if (File.Exists(paramList.Trim())) { try { var generator = new RazorGenerator(paramList.Trim(), string.Empty, new object()); generator.Init(); var result = generator.Render(); generator.OutPut(); OutputInformation("Entered string was: {0}", result); } catch (TemplateCompilationException exception) { OutputError(MRazorUtil.GetError(exception)); } catch (Exception ex) { OutputError("Error {0}", ex.Message); } } else { OutputError("Source file {0} not found", paramList); } return(Task.FromResult(true)); }
public override Task<bool> InvokeAsync(string paramList) { if (File.Exists(paramList.Trim())) { try { var generator = new RazorGenerator(paramList.Trim(),string.Empty, new object()); generator.Init(); var result = generator.Render(); generator.OutPut(); OutputInformation("Entered string was: {0}", result); } catch (TemplateCompilationException exception) { OutputError(MRazorUtil.GetError(exception)); } catch (Exception ex) { OutputError("Error {0}", ex.Message); } } else { OutputError("Source file {0} not found",paramList); } return Task.FromResult(true); }
public override bool Execute() { RazorProject project = this.CreateRazorProject(); RazorParser parser = new RazorParser(); this.PrintProjectData(project); List <string> filesToCompile = new List <string>(); Stopwatch watch = Stopwatch.StartNew(); foreach (RazorPage razorPage in parser.Parse(project)) { RazorGenerator generator = new RazorGenerator(this.CreateGeneratorOptions()); ProjectionResult result = generator.Generate(razorPage.Data); Directory.CreateDirectory(Path.GetDirectoryName(razorPage.IntermediatePath)); File.WriteAllText(razorPage.IntermediatePath, result.Content, Encoding.UTF8); this.PrintPageData(razorPage, razorPage.IntermediatePath); filesToCompile.Add(razorPage.IntermediatePath); } this.Compile = filesToCompile.ToArray(); this.PrintResultData(filesToCompile.Count, watch.ElapsedMilliseconds); return(true); }
public void RazorGeneratorCSharpTest() { var generator = new RazorGenerator(); var result = generator.Generate(model); Console.WriteLine(result); }
static void StarWarsReport() { try { var data = FetchStarWarsCharacters.Get(); // Step 03: Load HTML Template var htmlTemplate = EmbeddedResourceUtils.GetAppResource("StarWars.cshtml"); // Step 04: Generate HTML Contents var htmlReport = new RazorGenerator(htmlTemplate, data).Run(); } catch (Exception ex) { Console.WriteLine($"{ex.Message} - {MethodBase.GetCurrentMethod().Name}"); } }
static void EmailReport() { try { // Step 00: Setup Data EmailReport data = new EmailReport(); data.ReportName = "Some Report"; data.Version = 2; data.Problems.Add("wibble thing needs fixing"); data.Problems.Add("thingy-ma-bop needs straightening"); data.Problems.Add("doobery needs inverting"); // Step 01: Load HTML Template From embedded resource var htmlTemplate = EmbeddedResourceUtils.GetAppResource("EmailReport.cshtml"); // Step 02: Generate HTML Contents var htmlReport = new RazorGenerator(htmlTemplate, data).Run(); } catch (Exception ex) { Console.WriteLine($"{ex.Message} - {MethodBase.GetCurrentMethod().Name}"); } }
public override bool Execute() { RazorProject project = this.CreateRazorProject(); RazorParser parser = new RazorParser(); this.PrintProjectData(project); List <string> tempFiles = new List <string>(); string tempDir = this.CreateTempDirectory(); Stopwatch watch = Stopwatch.StartNew(); foreach (RazorPage razorPage in parser.Parse(project)) { string tempFile = this.GetTempFile(tempDir, razorPage); using (StreamWriter writer = this.GetStreamWriter(tempFile)) { RazorGenerator generator = new RazorGenerator(this.GetGeneratorOptions()); ProjectionResult result = generator.Generate(razorPage.Data); writer.Write(result.Content); } this.PrintPageData(razorPage, tempFile); tempFiles.Add(tempFile); } this.Compile = tempFiles.ToArray(); this.PrintResultData(tempFiles.Count, watch.ElapsedMilliseconds); return(true); }
public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress) { // SwitchDomainForRazorEngine(); byte[] resultBytes; try { var model = new RazorModel(); //set file name and namespace for model using model.DefaultNameSpace = wszDefaultNamespace; var info = new FileInfo(wszInputFilePath); if (info.Exists) { model.FileName = info.Name; } int iFound; uint itemId; ProjectItem item; VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1]; // obtain a reference to the current project as an IVsProject type IVsProject vsProject = VsHelper.ToVsProject(project); // this locates, and returns a handle to our source file, as a ProjectItem vsProject.IsDocumentInProject(wszInputFilePath, out iFound, pdwPriority, out itemId); // if our source file was found in the project (which it should have been) if (iFound != 0 && itemId != 0) { IServiceProvider oleSp; vsProject.GetItemContext(itemId, out oleSp); if (oleSp != null) { ServiceProvider sp = new ServiceProvider(oleSp); // convert our handle to a ProjectItem item = sp.GetService(typeof(ProjectItem)) as ProjectItem; } else { throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem"); } } else { throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem"); } var generator = new RazorGenerator(wszInputFilePath, bstrInputFileContents, model); generator.Init(); //get extension from header file if (!string.IsNullOrEmpty(generator.RazorTemplate.OutPutExtension)) { _extenstion = generator.RazorTemplate.OutPutExtension; } //generate code var result = generator.Render(); resultBytes = Encoding.UTF8.GetBytes(result); int outputLength = resultBytes.Length; rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength); Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength); pcbOutput = (uint)outputLength; return(VSConstants.S_OK); } catch (TemplateCompilationException tex) { //Display error in result template foreach (var compilerError in tex.CompilerErrors) { pGenerateProgress.GeneratorError(0, 1, compilerError.ErrorText, (uint)compilerError.Line, (uint)compilerError.Column); } var message = MRazorUtil.GetError(tex); resultBytes = Encoding.UTF8.GetBytes(message); int outputLength = resultBytes.Length; rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength); Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength); pcbOutput = (uint)outputLength; return(VSConstants.S_FALSE);// Change to E_Fail will display error in error list } catch (Exception ex) { var messageBuilder = new StringBuilder(ex.Message); messageBuilder.AppendLine(); if (ex.Source != null) { messageBuilder.Append(ex.Source); } messageBuilder.Append(ex.StackTrace); if (ex.InnerException != null) { messageBuilder.AppendLine(); messageBuilder.Append(ex.InnerException.Message + ex.InnerException.StackTrace); } resultBytes = Encoding.UTF8.GetBytes(messageBuilder.ToString()); int outputLength = resultBytes.Length; rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength); Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength); pcbOutput = (uint)outputLength; return(VSConstants.S_FALSE);// Change to E_Fail will display error in error list } //finally //{ // //unload domain for unload dll loaded from InputDllFolder // if (_domain != null) AppDomain.Unload(_domain); //} }
/// <summary> /// Mains the specified arguments. /// </summary> /// <param name="args">The arguments.</param> static int Main(string[] args) { if (AppDomain.CurrentDomain.IsDefaultAppDomain()) { return(RunInSecondAppDomain()); } System.Console.WriteLine("Sprint v.1.0 - Static Site Generator for Razor and markdown"); System.Console.WriteLine("Created by Pedro Fernandes @ Patreo"); System.Console.WriteLine("-----------------------------------------------------------"); System.Console.WriteLine(""); System.Console.WriteLine("Command line parameters:"); System.Console.WriteLine(" -o | -out: Output folder"); System.Console.WriteLine(" -t | -templates: Template folder where contains razor and assets files"); System.Console.WriteLine(""); CommandLineArgs _args = new CommandLineArgs(args); if (_args.TryGetValue("out", out string outputDir)) { OutputFolder = outputDir; } else { OutputFolder = Consts.OutputFolder; } if (_args.TryGetValue("template", out string templateDir)) { TemplateFolder = templateDir; } else { TemplateFolder = Consts.TemplateFolder; } ModulePresenter presenter = new ModulePresenter(); presenter.Initialize(); // Create output folder System.Console.Write("Creating output folder... "); Directories.CreateDirectory(OutputFolder); System.Console.WriteLine(Files.GetFileInfo(OutputFolder).FullName); // Copy all assets to output folder System.Console.Write("Copying assets folder to output folder... "); AssetsCopier copier = new AssetsCopier(Path.Combine(TemplateFolder, Consts.AssetsFolder)); foreach (IModuleInfo module in presenter.GetModulesByType(ModuleType.AssetsFolder)) { try { module.Execute(new ModuleParameter { Folder = copier.AssetsFolder }); } catch (Exception) { System.Console.WriteLine(""); System.Console.WriteLine($"Failed at {module.GetType().FullName} running { copier.AssetsFolder}"); System.Console.WriteLine(""); } } copier.CopyTo(Path.Combine(OutputFolder, Consts.AssetsFolder)); foreach (var fileInfo in Directories.FileList(Path.Combine(OutputFolder, Consts.AssetsFolder))) { foreach (IModuleInfo module in presenter.GetModulesByType(ModuleType.AssetsFile)) { try { module.Execute(new ModuleParameter { Folder = fileInfo.Directory.FullName, Filename = fileInfo.FullName }); } catch (Exception) { System.Console.WriteLine(""); System.Console.WriteLine($"Failed at {module.GetType().FullName} running {fileInfo.FullName}"); System.Console.WriteLine(""); } } } System.Console.WriteLine(System.IO.Path.Combine(Files.GetFileInfo(OutputFolder).FullName, Consts.AssetsFolder)); // Initialize render System.Console.WriteLine("Starting rendering content..."); IGenerator generator = new RazorGenerator(new DelegateTemplateManager(name => { return(Files.ReadAllText(Path.Combine(TemplateFolder, name))); })); // Generate pages and posts foreach (IModuleInfo module in presenter.GetModulesByType(ModuleType.ProcessingStarted)) { try { module.Execute(new ModuleParameter { Folder = OutputFolder }); } catch (Exception) { System.Console.WriteLine(""); System.Console.WriteLine($"Failed at {module.GetType().FullName} running {OutputFolder}"); System.Console.WriteLine(""); } } GenerateOutput(presenter, generator, new GenericRepository()); GenerateOutput(presenter, generator, new PageRepository()); GenerateOutput(presenter, generator, new PostRepository()); foreach (IModuleInfo module in presenter.GetModulesByType(ModuleType.ProcessingEnded)) { try { module.Execute(new ModuleParameter { Folder = OutputFolder }); } catch (Exception) { System.Console.WriteLine(""); System.Console.WriteLine($"Failed at {module.GetType().FullName} running {OutputFolder}"); System.Console.WriteLine(""); } } System.Console.WriteLine(""); System.Console.WriteLine("Done."); System.Console.WriteLine("Thanks for your patience."); return(0); }
public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress) { // SwitchDomainForRazorEngine(); byte[] resultBytes; try { var model = new RazorModel(); //set file name and namespace for model using model.DefaultNameSpace = wszDefaultNamespace; var info=new FileInfo(wszInputFilePath); if (info.Exists) { model.FileName = info.Name; } int iFound; uint itemId; ProjectItem item; VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1]; // obtain a reference to the current project as an IVsProject type IVsProject vsProject = VsHelper.ToVsProject(project); // this locates, and returns a handle to our source file, as a ProjectItem vsProject.IsDocumentInProject(wszInputFilePath, out iFound, pdwPriority, out itemId); // if our source file was found in the project (which it should have been) if (iFound != 0 && itemId != 0) { IServiceProvider oleSp; vsProject.GetItemContext(itemId, out oleSp); if (oleSp != null) { ServiceProvider sp = new ServiceProvider(oleSp); // convert our handle to a ProjectItem item = sp.GetService(typeof(ProjectItem)) as ProjectItem; } else throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem"); } else throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem"); var generator = new RazorGenerator(wszInputFilePath,bstrInputFileContents, model); generator.Init(); //get extension from header file if (!string.IsNullOrEmpty(generator.RazorTemplate.OutPutExtension)) { _extenstion = generator.RazorTemplate.OutPutExtension; } //generate code var result = generator.Render(); resultBytes = Encoding.UTF8.GetBytes(result); int outputLength = resultBytes.Length; rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength); Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength); pcbOutput = (uint) outputLength; return VSConstants.S_OK; } catch (TemplateCompilationException tex) { //Display error in result template foreach (var compilerError in tex.CompilerErrors) { pGenerateProgress.GeneratorError(0, 1, compilerError.ErrorText, (uint) compilerError.Line, (uint) compilerError.Column); } var message = MRazorUtil.GetError(tex); resultBytes = Encoding.UTF8.GetBytes(message); int outputLength = resultBytes.Length; rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength); Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength); pcbOutput = (uint) outputLength; return VSConstants.S_FALSE;// Change to E_Fail will display error in error list } catch (Exception ex) { var messageBuilder =new StringBuilder( ex.Message); messageBuilder.AppendLine(); if (ex.Source != null) messageBuilder.Append(ex.Source); messageBuilder.Append(ex.StackTrace); if (ex.InnerException != null) { messageBuilder.AppendLine(); messageBuilder.Append(ex.InnerException.Message + ex.InnerException.StackTrace); } resultBytes = Encoding.UTF8.GetBytes(messageBuilder.ToString()); int outputLength = resultBytes.Length; rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength); Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength); pcbOutput = (uint) outputLength; return VSConstants.S_FALSE;// Change to E_Fail will display error in error list } //finally //{ // //unload domain for unload dll loaded from InputDllFolder // if (_domain != null) AppDomain.Unload(_domain); //} }