Example #1
0
        private static string GenerateCodeFromRazorString(WebPageRazorHost host, string razorString, string virtualPath)
        {

            // Create Razor engine and use it to generate a CodeCompileUnit
            var engine = new RazorTemplateEngine(host);
            GeneratorResults results = null;

            using (StringReader reader = new StringReader(razorString))
            {
                results = engine.GenerateCode(reader, className: null, rootNamespace: null,
                    sourceFileName: host.PhysicalPath);
            }

            if (!results.Success)
            {
                throw CreateExceptionFromParserError(results.ParserErrors.Last(), virtualPath);
            }

            // Use CodeDom to generate source code from the CodeCompileUnit
            using (var codeDomProvider = new CSharpCodeProvider())
            {
                using (var srcFileWriter = new StringWriter())
                {
                    codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, srcFileWriter,
                        new CodeGeneratorOptions());

                    return srcFileWriter.ToString();
                }
            }
        }
Example #2
0
        internal static WebPageRazorHost CreateHostFromConfigCore(RazorWebSectionGroup config, string virtualPath, string physicalPath)
        {
            // Use the virtual path to select a host environment for the generated code
            // Do this check here because the App_Code host can't be overridden.

            // Make the path app relative
            virtualPath = EnsureAppRelative(virtualPath);

            if (virtualPath.StartsWith("~/App_Code", StringComparison.OrdinalIgnoreCase))
            {
                // Under App_Code => It's a Web Code file
                return(new WebCodeRazorHost(virtualPath, physicalPath));
            }

            WebRazorHostFactory factory = null;

            if (config != null && config.Host != null && !String.IsNullOrEmpty(config.Host.FactoryType))
            {
                Func <WebRazorHostFactory> factoryCreator = _factories.GetOrAdd(config.Host.FactoryType, CreateFactory);
                Debug.Assert(factoryCreator != null); // CreateFactory should throw if there's an error creating the factory
                factory = factoryCreator();
            }

            WebPageRazorHost host = (factory ?? new WebRazorHostFactory()).CreateHost(virtualPath, physicalPath);

            if (config != null && config.Pages != null)
            {
                ApplyConfigurationToHost(config.Pages, host);
            }

            return(host);
        }
        public static void ApplyConfigurationToHost(RazorPagesSection config, WebPageRazorHost host)
        {
            host.DefaultPageBaseClass = config.PageBaseType;

            // Add imports
            foreach (string import in config.Namespaces.OfType <NamespaceInfo>().Select(ns => ns.Namespace))
            {
                host.NamespaceImports.Add(import);
            }
        }
Example #4
0
        protected internal virtual WebPageRazorHost CreateHost()
        {
            // Get the host from config
            WebPageRazorHost configuredHost = GetHostFromConfig();

            // Fire the event
            CompilingPathEventArgs args = new CompilingPathEventArgs(VirtualPath, configuredHost);

            OnBeforeCompilePath(args);

            // Return the host provided in the args, which may have been changed by the handler
            return(args.Host);
        }
        public static void ApplyConfigurationToHost(RazorPagesSection config, WebPageRazorHost host)
        {
            host.DefaultPageBaseClass = config.PageBaseType;

            // Add imports
            foreach (string import in config.Namespaces.OfType<NamespaceInfo>().Select(ns => ns.Namespace))
            {
                host.NamespaceImports.Add(import);
            }
        }
Example #6
0
        static void Main(string[] args)
        {
            string templatebasename = "RazorEngine.Templating.TemplateBase";
            var namespaces = new List<string>();
            if (args.Length > 0)
            {
                templatebasename = args[0];
            }
            for (int i = 1; i < args.Length; i++ )
            {
                namespaces.Add(args[i]);
            }

            var filecount = 0;

            // for each .cshtml file under the working directory, generate a .cs file if it has changed.
            foreach (var templatepath in Directory.EnumerateFiles(Environment.CurrentDirectory, "*.cshtml", SearchOption.AllDirectories))
            {
                FileInfo fitemplate = new FileInfo(templatepath);
                FileInfo ficode = new FileInfo(templatepath + ".cs");
                if (!ficode.Exists || ficode.LastWriteTimeUtc < fitemplate.LastWriteTimeUtc)
                {
                    // get classname from path
                    var cn = fitemplate.Name.Substring(0, fitemplate.Name.IndexOf('.'));
                    var pt = fitemplate.DirectoryName.Split(new char[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
                    var ns = pt[pt.Length - 1];
                    for (var i = pt.Length - 2; i > 0; i--)
                    {
                        ns = pt[i] + "." + ns;
                        if (pt[i + 1] == "Views") break;
                    }

                    var prp = fitemplate.FullName.Substring(fitemplate.FullName.IndexOf(@"\Views\")).Replace('\\', '/');

                    string template =
                         File.ReadAllText(fitemplate.FullName);
                    var host =
                        new WebPageRazorHost("~" + prp, fitemplate.FullName);
                    //new RazorEngineHost(new CSharpRazorCodeLanguage());
                    //new WebCodeRazorHost("~"+prp, fitemplate.FullName);
                    var rte = new RazorTemplateEngine(host);

                    //Razor.SetTemplateBaseType(typeof(TemplateBase<>));

                    string baseTypeName = templatebasename;

                    if (template.StartsWith("@model"))
                    {
                        var l1 = template.IndexOf("\n");
                        var modelTypeName = template.Substring(6, l1 - 6).Trim();
                        template = template.Substring(l1).Trim();
                        baseTypeName = templatebasename + "<" + modelTypeName + ">";
                    }
                    //else if (cn == "_ViewStart")
                    //{
                    //    baseTypeName = "System.Web.WebPages.StartPage";
                    //}
                    else
                    {
                        baseTypeName = templatebasename + "<dynamic>";
                    }

                    //host.DefaultNamespace = "";

                    host.DefaultPageBaseClass = baseTypeName;

                    host.NamespaceImports.Add("System.Web.Mvc");
                    host.NamespaceImports.Add("System.Web.Mvc.Html");

                    //string result =
                    //Razor.ParseToCode(template, null, cn, baseTypeName, ns);

                    GeneratorResults results = null;
                    using (var reader = new StringReader(template))
                    {
                        results = rte.GenerateCode(reader, cn, ns, null);
                    }
                    StringBuilder builder = new StringBuilder();

                    builder.AppendLine("using System.Web.Mvc;");
                    builder.AppendLine("using System.Web.Mvc.Html;");
                    builder.AppendLine("using System.Web.Mvc.Ajax;");

                    foreach (var v in namespaces)
                    {
                        builder.AppendLine("using "+v+";");
                    }

                    using (var writer = new StringWriter(builder))
                    {
                        new CSharpCodeProvider().GenerateCodeFromCompileUnit(results.GeneratedCode, writer, null);
                    }
                    builder.Replace("#line hidden", "#line 1 \"" + fitemplate.Name + "\"");
                    File.WriteAllText(ficode.FullName, builder.ToString());
                    Console.WriteLine("Updated {0}.{1}", ns, cn);
                    filecount++;
                }
            }
            Console.WriteLine("Done - updated {0} files", filecount);

            Console.ReadLine();
        }
 private void OnCodeGenerationCompleted(CodeCompileUnit codeCompileUnit, WebPageRazorHost host) =>
    CodeGenerationCompleted?.Invoke(this, new CodeGenerationCompleteEventArgs(host.VirtualPath, host.PhysicalPath, codeCompileUnit));
        private static Assembly CompileToAssembly(WebPageRazorHost host, SyntaxTree syntaxTree)
        {
            var compilation = CSharpCompilation.Create(
                "RoslynRazor", // Note: using a fixed assembly name, which doesn't matter as long as we don't expect cross references of generated assemblies
                new[] { syntaxTree },
                BuildManager.GetReferencedAssemblies().OfType<Assembly>().Select(ResolveReference),
                new CSharpCompilationOptions(
                    outputKind: OutputKind.DynamicallyLinkedLibrary,
                    assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
                    optimizationLevel: host.DefaultDebugCompilation ? OptimizationLevel.Debug : OptimizationLevel.Release));

            using (var dllStream = new MemoryStream())
            using (var pdbStream = new MemoryStream())
            {
                EmitResult emitResult = compilation.Emit(dllStream, pdbStream);

                if (!emitResult.Success)
                {
                    Diagnostic diagnostic = emitResult.Diagnostics.First(x => x.Severity == DiagnosticSeverity.Error);
                    string message = diagnostic.ToString();
                    LinePosition linePosition = diagnostic.Location.GetMappedLineSpan().StartLinePosition;

                    throw new HttpParseException(message, null, host.VirtualPath, null, linePosition.Line + 1);
                }

                return Assembly.Load(dllStream.GetBuffer(), pdbStream.GetBuffer());
            }
        }
        private static SyntaxTree GetSyntaxTree(WebPageRazorHost host, GeneratorResults razorResult)
        {
            // Use CodeDom to generate source code from the CodeCompileUnit
            // Use roslyn to parse it back
            using (var codeDomProvider = CodeDomProvider.CreateProvider(host.CodeLanguage.LanguageName))
            using (var viewCodeStream = new MemoryStream())
            using (var viewCodeWriter = new StreamWriter(viewCodeStream))
            {
                codeDomProvider.GenerateCodeFromCompileUnit(razorResult.GeneratedCode, viewCodeWriter, new CodeGeneratorOptions());
                viewCodeWriter.Flush();
                viewCodeStream.Position = 0;
                var sourceText = SourceText.From(viewCodeStream);

                // We need a different file path for the generated file, otherwise breakpoints won't get
                // hit due to #line directives pointing at the original .cshtml. If we'd want breakpoint
                // in the generated .cs code, we'd have to dump them somewhere on disk, and specify the path here.
                var sourcePath = string.IsNullOrEmpty(host.PhysicalPath)
                    ? host.VirtualPath // yay virtual paths, won't point at the original file
                    : Path.ChangeExtension(host.PhysicalPath, ".roslynviewengine");
                return SyntaxFactory.ParseSyntaxTree(sourceText, path: sourcePath);
            }
        }
 private GeneratorResults RunRazorGenerator(string virtualPath, WebPageRazorHost host)
 {
     var file = HostingEnvironment.VirtualPathProvider.GetFile(virtualPath);
     var engine = new RazorTemplateEngine(host);
     using (var viewStream = file.Open())
     using (var viewReader = new StreamReader(viewStream))
     {
         var razorResult = engine.GenerateCode(viewReader, className: null, rootNamespace: null, sourceFileName: host.PhysicalPath);
         if (!razorResult.Success)
         {
             throw CreateExceptionFromParserError(razorResult.ParserErrors.Last(), virtualPath);
         }
         OnCodeGenerationCompleted(razorResult.GeneratedCode, host);
         return razorResult;
     }
 }
        private static string GenerateCodeFromRazorTemplate(WebPageRazorHost host, string virtualPath)
        {
            // create Razor engine and use it to generate a CodeCompileUnit
            var engine = new RazorTemplateEngine(host);
            var file = HostingEnvironment.VirtualPathProvider.GetFile(virtualPath);

            // load the source (eg cshtml) code
            string code;
            using (var stream = file.Open())
            using (TextReader reader = new StreamReader(stream))
                code = reader.ReadToEnd();

            // generate the target (C#) code
            ITextBuffer textBuffer = new SeekableTextReader(code);
            var results = engine.GenerateCode(textBuffer, null, null, virtualPath);
            if (!results.Success)
                ThrowExceptionFromParserError(virtualPath, code, results.ParserErrors.Last());

            // use CodeDom to generate source code from the CodeCompileUnit
            var codeDomProvider = new CSharpCodeProvider();
            var srcFileWriter = new StringWriter();
            codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, srcFileWriter, new CodeGeneratorOptions());

            return srcFileWriter.ToString();
        }
 internal MinifyHtmlMvcWebPageRazorHost(WebPageRazorHost host, MinifyHtmlMinifier minifier, string virtualPath, string physicalPath)
     : base(virtualPath, physicalPath)
 {
     _host = host;
     _minifier = minifier;
 }
        private string GenerateCodeFromRazorTemplate(WebPageRazorHost host, string virtualPath)
        {
            // Create Razor engine and use it to generate a CodeCompileUnit
            var engine = new RazorTemplateEngine(host);
            GeneratorResults results = null;
            VirtualFile file = HostingEnvironment.VirtualPathProvider.GetFile(virtualPath);
            using (var stream = file.Open())
            {
                using (TextReader reader = new StreamReader(stream))
                {
                    results = engine.GenerateCode(reader, className: null, rootNamespace: null, sourceFileName: host.PhysicalPath);
                }
            }

            if (!results.Success)
            {
                throw CreateExceptionFromParserError(results.ParserErrors.Last(), virtualPath);
            }

            // Use CodeDom to generate source code from the CodeCompileUnit
            var codeDomProvider = new CSharpCodeProvider();
            var srcFileWriter = new StringWriter();
            codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, srcFileWriter, new CodeGeneratorOptions());

            return srcFileWriter.ToString();
        }
Example #14
0
        public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            string templatebasename = "RazorEngine.Templating.TemplateBase";
            FileInfo fitemplate = new FileInfo(wszInputFilePath);
            FileInfo ficode = new FileInfo(wszInputFilePath.Replace(".cshtml", ".cs"));

            if (!ficode.Exists || ficode.LastWriteTimeUtc < fitemplate.LastWriteTimeUtc)
            {
                // get classname from path
                var cn = fitemplate.Name.Substring(0, fitemplate.Name.IndexOf('.'));
                // var pt = fitemplate.DirectoryName.Split(new char[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);

                var ns = wszDefaultNamespace;

                string template = File.ReadAllText(fitemplate.FullName);
                var host = new WebPageRazorHost(wszInputFilePath);
                //new WebPageRazorHost("~" + , fitemplate.FullName);
                //new RazorEngineHost(new CSharpRazorCodeLanguage());
                //new WebCodeRazorHost("~"+prp, fitemplate.FullName);
                var rte = new RazorTemplateEngine(host);

                //Razor.SetTemplateBaseType(typeof(TemplateBase<>));

                string baseTypeName = templatebasename;

                if (template.StartsWith("@model"))
                {
                    var l1 = template.IndexOf("\n");
                    var modelTypeName = template.Substring(6, l1 - 6).Trim();
                    template = template.Substring(l1).Trim();
                    baseTypeName = templatebasename + "<" + modelTypeName + ">";
                }
                //else if (cn == "_ViewStart")
                //{
                //    baseTypeName = "System.Web.WebPages.StartPage";
                //}
                else
                {
                    baseTypeName = templatebasename + "<dynamic>";
                }

                //host.DefaultNamespace = "";

                host.DefaultPageBaseClass = baseTypeName;

                host.NamespaceImports.Add("System.Web.Mvc");
                host.NamespaceImports.Add("System.Web.Mvc.Html");

                //string result =
                //Razor.ParseToCode(template, null, cn, baseTypeName, ns);

                GeneratorResults results = null;
                using (var reader = new StringReader(template))
                {
                    results = rte.GenerateCode(reader, cn, ns, null);
                }
                StringBuilder builder = new StringBuilder();
                //builder.AppendLine("using System.Web.Mvc;");
                //builder.AppendLine("using System.Web.Mvc.Html;");

                using (var writer = new StringWriter(builder))
                {
                    new CSharpCodeProvider().GenerateCodeFromCompileUnit(results.GeneratedCode, writer, null);
                }
                builder.Replace("#line hidden", "#line 1 \"" + fitemplate.Name + "\"");
                File.WriteAllText(ficode.FullName, builder.ToString());
                Console.WriteLine("Updated {0}.{1}", ns, cn);

                byte[] bytes = Encoding.UTF8.GetBytes(builder.ToString());
                int length = bytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(length);
                Marshal.Copy(bytes, 0, rgbOutputFileContents[0], length);

                pcbOutput = (uint)length;
                return VSConstants.S_OK;
            }
            else
            {
                rgbOutputFileContents = new IntPtr[] { };
                pcbOutput = 0;
                return 0;
            }
        }