Esempio n. 1
1
        private static string BuildErrorMessage(EmitResult result, ViewLocationResult viewLocationResult, string sourceCode)
        {
            var failures = result.Diagnostics
                .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error)
                .ToArray();

            var fullTemplateName = viewLocationResult.Location + "/" + viewLocationResult.Name + "." + viewLocationResult.Extension;
            var templateLines = GetViewBodyLines(viewLocationResult);
            var compilationSource = GetCompilationSource(sourceCode);
            var errorMessages = BuildErrorMessages(failures, templateLines, compilationSource);

            var lineNumber = 1;

            var errorDetails = string.Format(
                "Error compiling template: <strong>{0}</strong><br/><br/>Errors:<br/>{1}<br/><br/>Details:<br/>{2}<br/><br/>Compilation Source:<br/><pre><code>{3}</code></pre>",
                fullTemplateName,
                errorMessages,
                templateLines.Aggregate((s1, s2) => s1 + "<br/>" + s2),
                compilationSource.Aggregate((s1, s2) => s1 + "<br/>Line " + lineNumber++ + ":\t" + s2));

            return errorDetails;
        }
Esempio n. 2
0
        /// <summary>
        /// Renders the view.
        /// </summary>
        /// <param name="viewLocationResult">A <see cref="ViewLocationResult"/> instance, containing information on how to get the view template.</param>
        /// <param name="model">The model that should be passed into the view</param>
        /// <param name="renderContext">The render context.</param>
        /// <param name="isPartial">Used by HtmlHelpers to declare a view as partial</param>
        /// <returns>A response.</returns>
        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext, bool isPartial)
        {
            Assembly referencingAssembly = null;

            var response = new HtmlResponse();

            response.Contents = stream =>
            {
                var writer =
                    new StreamWriter(stream);

                var view = this.GetViewInstance(viewLocationResult, renderContext, model);

                view.ExecuteView(null, null);

                var body = view.Body;
                var sectionContents = view.SectionContents;

                var layout = view.HasLayout ? view.Layout : GetViewStartLayout(model, renderContext, referencingAssembly, isPartial);

                var root = string.IsNullOrWhiteSpace(layout);

                while (!root)
                {
                    var viewLocation =
                        renderContext.LocateView(layout, model);

                    if (viewLocation == null)
                    {
                        throw new InvalidOperationException("Unable to locate layout: " + layout);
                    }

                    view = this.GetViewInstance(viewLocation, renderContext, model);

                    view.ExecuteView(body, sectionContents);

                    body = view.Body;
                    sectionContents = view.SectionContents;

                    layout = view.HasLayout ? view.Layout : GetViewStartLayout(model, renderContext, referencingAssembly, isPartial);

                    root = !view.HasLayout;
                }

                writer.Write(body);
                writer.Flush();
            };

            return response;
        }
Esempio n. 3
0
        /// <summary>
        /// Renders the view.
        /// </summary>
        /// <param name="viewLocationResult">A <see cref="ViewLocationResult"/> instance, containing information on how to get the view template.</param>
        /// <param name="model">The model that should be passed into the view</param>
        /// <param name="renderContext">The render context.</param>
        /// <returns>A response.</returns>
        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            Assembly referencingAssembly = null;

            if (model != null)
            {
                var underlyingSystemType = model.GetType().UnderlyingSystemType;
                if (underlyingSystemType != null)
                {
                    referencingAssembly = Assembly.GetAssembly(underlyingSystemType);
                }
            }

            var response = new HtmlResponse();

            response.Contents = stream =>
            {
                var writer = new StreamWriter(stream);
                var view = this.GetViewInstance(viewLocationResult, renderContext, referencingAssembly, model);
                view.ExecuteView(null, null);
                var body = view.Body;
                var sectionContents = view.SectionContents;
                var root = !view.HasLayout;
                var layout = view.Layout;

                while (!root)
                {
                    view = this.GetViewInstance(renderContext.LocateView(layout, model), renderContext, referencingAssembly, model);
                    view.ExecuteView(body, sectionContents);

                    body = view.Body;
                    sectionContents = view.SectionContents;
                    root = !view.HasLayout;
                    layout = view.Layout;
                }

                writer.Write(body);
                writer.Flush();
            };

            return response;
        }
Esempio n. 4
0
        private static string BuildErrorMessage(EmitResult result, ViewLocationResult viewLocationResult, string sourceCode)
        {
            var failures = result.Diagnostics
                           .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error)
                           .ToArray();

            var fullTemplateName  = viewLocationResult.Location + "/" + viewLocationResult.Name + "." + viewLocationResult.Extension;
            var templateLines     = GetViewBodyLines(viewLocationResult);
            var compilationSource = GetCompilationSource(sourceCode);
            var errorMessages     = BuildErrorMessages(failures, templateLines, compilationSource);

            var lineNumber = 1;

            var errorDetails = string.Format(
                "Template: <strong>{0}</strong><br/><br/>Errors:<ul>{1}</ul>Details:<br/><pre>{2}</pre><br/>Compilation Source:<br/><pre><code>{3}</code></pre>",
                fullTemplateName,
                errorMessages,
                templateLines.Aggregate((s1, s2) => s1 + "<br/>" + s2),
                compilationSource.Aggregate((s1, s2) => s1 + "<br/><span class='lineNumber'>Line " + lineNumber++ + ":</span>\t" + s2.Replace("<", "&gt;").Replace(">", "&lt;")));

            return(errorDetails);
        }
Esempio n. 5
0
        private Func<INancyRazorView> GenerateRazorViewFactory(IRazorViewRenderer renderer, GeneratorResults generatorResults, Type passedModelType, ViewLocationResult viewLocationResult)
        {
            var modelType = GetModelTypeFromGeneratedCode(generatorResults, passedModelType);
            var sourceCode = string.Empty;

            if (this.razorConfiguration != null)
            {
                if (this.razorConfiguration.AutoIncludeModelNamespace)
                {
                    AddModelNamespace(generatorResults, modelType);
                }
            }

            using (var writer = new StringWriter())
            {
                renderer.Provider.GenerateCodeFromCompileUnit(generatorResults.GeneratedCode, writer, new CodeGeneratorOptions());
                sourceCode = writer.ToString();
            }

            var compilation = CSharpCompilation.Create(
                assemblyName: string.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N")),
                syntaxTrees: new[] { CSharpSyntaxTree.ParseText(sourceCode) },
                references: this.GetMetadataReferences().Value,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                var result = compilation.Emit(ms);

                if (!result.Success)
                {
                    return () => new NancyRazorErrorView(BuildErrorMessage(result, viewLocationResult, sourceCode), this.traceConfiguration);
                }

                ms.Seek(0, SeekOrigin.Begin);
                var viewAssembly = Assembly.Load(ms.ToArray());

                return () => (INancyRazorView) Activator.CreateInstance(viewAssembly.GetType("RazorOutput.RazorView"));
            }
        }
Esempio n. 6
0
        private Func<INancyRazorView> GetCompiledViewFactory(TextReader reader, Type passedModelType, ViewLocationResult viewLocationResult)
        {
            var engine = new RazorTemplateEngine(this.viewRenderer.Host);

            var razorResult = engine.GenerateCode(reader, null, null, "roo");

            var viewFactory = this.GenerateRazorViewFactory(this.viewRenderer, razorResult, passedModelType, viewLocationResult);

            return viewFactory;
        }
Esempio n. 7
0
 private NancyRazorViewBase GetViewInstance(ViewLocationResult viewLocationResult, IRenderContext renderContext, Assembly referencingAssembly, dynamic model)
 {
     var view = this.GetOrCompileView(viewLocationResult, renderContext, referencingAssembly);
     view.Initialize(this, renderContext, model);
     return view;
 }
Esempio n. 8
0
        private INancyRazorView GetOrCompileView(ViewLocationResult viewLocationResult, IRenderContext renderContext, Assembly referencingAssembly, Type passedModelType)
        {
            var viewFactory = renderContext.ViewCache.GetOrAdd(
                viewLocationResult,
                x =>
                {
                    using (var reader = x.Contents.Invoke())
                        return this.GetCompiledViewFactory(x.Extension, reader, referencingAssembly, passedModelType, viewLocationResult);
                });

            var view = viewFactory.Invoke();

            return view;
        }
Esempio n. 9
0
        private Func<INancyRazorView> GenerateRazorViewFactory(IRazorViewRenderer viewRenderer, GeneratorResults razorResult, Assembly referencingAssembly, Type passedModelType, ViewLocationResult viewLocationResult)
        {
            var outputAssemblyName =
                Path.Combine(Path.GetTempPath(), String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N")));

            var modelType =
                FindModelType(razorResult.Document, passedModelType, viewRenderer.ModelCodeGenerator);

            var assemblies = new List<string>
            {
                GetAssemblyPath(typeof(System.Runtime.CompilerServices.CallSite)),
                GetAssemblyPath(typeof(IHtmlString)),
                GetAssemblyPath(Assembly.GetExecutingAssembly()),
                GetAssemblyPath(modelType)
            };

            assemblies.AddRange(AppDomainAssemblyTypeScanner.Assemblies.Select(GetAssemblyPath));

            if (referencingAssembly != null)
            {
                assemblies.Add(GetAssemblyPath(referencingAssembly));
            }

            if (this.razorConfiguration != null)
            {
                var assemblyNames = this.razorConfiguration.GetAssemblyNames();
                if (assemblyNames != null)
                {
                    assemblies.AddRange(assemblyNames.Select(Assembly.Load).Select(GetAssemblyPath));
                }

                if (this.razorConfiguration.AutoIncludeModelNamespace)
                {
                    AddModelNamespace(razorResult, modelType);
                }
            }

            assemblies = assemblies
                .Union(viewRenderer.Assemblies)
                .ToList();

            var compilerParameters =
                new CompilerParameters(assemblies.ToArray(), outputAssemblyName);

            CompilerResults results;
            lock (this.compileLock)
            {
                results = viewRenderer.Provider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode);
            }

            if (results.Errors.HasErrors)
            {
                var output = new string[results.Output.Count];
                results.Output.CopyTo(output, 0);

                var fullTemplateName = viewLocationResult.Location + "/" + viewLocationResult.Name + "." + viewLocationResult.Extension;
                var templateLines = GetViewBodyLines(viewLocationResult);
                var errors = results.Errors.OfType<CompilerError>().Where(ce => !ce.IsWarning).ToArray();
                var errorMessages = BuildErrorMessages(errors);
                var compilationSource = this.GetCompilationSource(viewRenderer.Provider, razorResult.GeneratedCode);

                MarkErrorLines(errors, templateLines);

                var lineNumber = 1;

                var errorDetails = string.Format(
                                        "Error compiling template: <strong>{0}</strong><br/><br/>Errors:<br/>{1}<br/><br/>Details:<br/>{2}<br/><br/>Compilation Source:<br/><pre><code>{3}</code></pre>",
                                        fullTemplateName,
                                        errorMessages,
                                        templateLines.Aggregate((s1, s2) => s1 + "<br/>" + s2),
                                        compilationSource.Aggregate((s1, s2) => s1 + "<br/>Line " + lineNumber++ + ":\t" + s2));

                return () => new NancyRazorErrorView(errorDetails);
            }

            var assembly = Assembly.LoadFrom(outputAssemblyName);
            if (assembly == null)
            {
                const string error = "Error loading template assembly";
                return () => new NancyRazorErrorView(error);
            }

            var type = assembly.GetType("RazorOutput.RazorView");
            if (type == null)
            {
                var error = String.Format("Could not find type RazorOutput.Template in assembly {0}", assembly.FullName);
                return () => new NancyRazorErrorView(error);
            }

            if (Activator.CreateInstance(type) as INancyRazorView == null)
            {
                const string error = "Could not construct RazorOutput.Template or it does not inherit from INancyRazorView";
                return () => new NancyRazorErrorView(error);
            }

            return () => (INancyRazorView)Activator.CreateInstance(type);
        }
Esempio n. 10
0
 /// <summary>
 /// Renders the view.
 /// </summary>
 /// <param name="viewLocationResult">A <see cref="ViewLocationResult"/> instance, containing information on how to get the view template.</param>
 /// <param name="model">The model that should be passed into the view</param>
 /// <param name="renderContext">The render context.</param>
 /// <returns>A response.</returns>
 public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
 {
     return RenderView(viewLocationResult, model, renderContext, false);
 }
 /// <summary>
 /// initializes a new instance of the <see cref="RazorLayoutNotFoundException"/>
 /// </summary>
 /// <param name="layoutName">The name of the layout that could not be found.</param>
 /// <param name="innerViewLocationResult">The location of the view or layout that the missing layout should wrap.</param>
 public RazorLayoutNotFoundException(string layoutName, ViewLocationResult innerViewLocationResult)
     : base(String.Format("The view '{0} {1}' referenced layout '{2}' but it could not be found.", innerViewLocationResult.Location, innerViewLocationResult.Name, layoutName))
 {
 }
Esempio n. 12
0
        private Func <INancyRazorView> GenerateRazorViewFactory(IRazorViewRenderer viewRenderer, GeneratorResults razorResult, Assembly referencingAssembly, Type passedModelType, ViewLocationResult viewLocationResult)
        {
            var outputAssemblyName =
                Path.Combine(Path.GetTempPath(), String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N")));

            var modelType = (Type)razorResult.GeneratedCode.Namespaces[0].Types[0].UserData["ModelType"]
                            ?? passedModelType
                            ?? typeof(object);

            var assemblies = new List <string>
            {
                GetAssemblyPath(typeof(CallSite)),
                GetAssemblyPath(typeof(IHtmlString)),
                GetAssemblyPath(Assembly.GetExecutingAssembly()),
                GetAssemblyPath(modelType)
            };

            assemblies.AddRange(this.assemblyCatalog.GetAssemblies().Select(GetAssemblyPath));

            if (referencingAssembly != null)
            {
                assemblies.Add(GetAssemblyPath(referencingAssembly));
            }

            if (this.razorConfiguration != null)
            {
                var assemblyNames = this.razorConfiguration.GetAssemblyNames();
                if (assemblyNames != null)
                {
                    assemblies.AddRange(assemblyNames.Select(Assembly.Load).Select(GetAssemblyPath));
                }

                if (this.razorConfiguration.AutoIncludeModelNamespace)
                {
                    AddModelNamespace(razorResult, modelType);
                }
            }

            assemblies = assemblies
                         .Union(viewRenderer.Assemblies)
                         .ToList();

            var compilerParameters =
                new CompilerParameters(assemblies.ToArray(), outputAssemblyName);

            CompilerResults results;

            lock (this.compileLock)
            {
                results = viewRenderer.Provider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode);
            }

            if (results.Errors.HasErrors)
            {
                var output = new string[results.Output.Count];
                results.Output.CopyTo(output, 0);

                var fullTemplateName  = viewLocationResult.Location + "/" + viewLocationResult.Name + "." + viewLocationResult.Extension;
                var templateLines     = GetViewBodyLines(viewLocationResult);
                var errors            = results.Errors.OfType <CompilerError>().Where(ce => !ce.IsWarning).ToArray();
                var errorMessages     = BuildErrorMessages(errors);
                var compilationSource = this.GetCompilationSource(viewRenderer.Provider, razorResult.GeneratedCode);

                MarkErrorLines(errors, templateLines);

                var lineNumber = 1;

                var errorDetails = string.Format(
                    "Error compiling template: <strong>{0}</strong><br/><br/>Errors:<br/>{1}<br/><br/>Details:<br/>{2}<br/><br/>Compilation Source:<br/><pre><code>{3}</code></pre>",
                    fullTemplateName,
                    errorMessages,
                    templateLines.Aggregate((s1, s2) => s1 + "<br/>" + s2),
                    compilationSource.Aggregate((s1, s2) => s1 + "<br/>Line " + lineNumber++ + ":\t" + s2));

                return(() => new NancyRazorErrorView(errorDetails, this.traceConfiguration));
            }

            var assembly = Assembly.LoadFrom(outputAssemblyName);

            if (assembly == null)
            {
                const string error = "Error loading template assembly";
                return(() => new NancyRazorErrorView(error, this.traceConfiguration));
            }

            var type = assembly.GetType("RazorOutput.RazorView");

            if (type == null)
            {
                var error = String.Format("Could not find type RazorOutput.Template in assembly {0}", assembly.FullName);
                return(() => new NancyRazorErrorView(error, this.traceConfiguration));
            }

            if (Activator.CreateInstance(type) as INancyRazorView == null)
            {
                const string error = "Could not construct RazorOutput.Template or it does not inherit from INancyRazorView";
                return(() => new NancyRazorErrorView(error, this.traceConfiguration));
            }

            return(() => (INancyRazorView)Activator.CreateInstance(type));
        }
Esempio n. 13
0
        private Func<NancyRazorViewBase> GetCompiledViewFactory(string extension, TextReader reader, Assembly referencingAssembly, Type passedModelType, ViewLocationResult viewLocationResult)
        {
            var renderer = this.viewRenderers.First(x => x.Extension.Equals(extension, StringComparison.OrdinalIgnoreCase));

            var engine = this.GetRazorTemplateEngine(renderer.Host);

            var razorResult = engine.GenerateCode(reader, sourceFileName: "placeholder");

            var viewFactory = this.GenerateRazorViewFactory(renderer.Provider, razorResult, referencingAssembly, renderer.Assemblies, passedModelType, viewLocationResult);

            return viewFactory;
        }
Esempio n. 14
0
        private Func <INancyRazorView> GenerateRazorViewFactory(IRazorViewRenderer renderer, GeneratorResults generatorResults, Type passedModelType, ViewLocationResult viewLocationResult)
        {
            var modelType  = GetModelTypeFromGeneratedCode(generatorResults, passedModelType);
            var sourceCode = string.Empty;

            if (this.razorConfiguration != null)
            {
                if (this.razorConfiguration.AutoIncludeModelNamespace)
                {
                    AddModelNamespace(generatorResults, modelType);
                }
            }

            using (var writer = new StringWriter())
            {
                renderer.Provider.GenerateCodeFromCompileUnit(generatorResults.GeneratedCode, writer, new CodeGeneratorOptions());
                sourceCode = writer.ToString();
            }

            var compilation = CSharpCompilation.Create(
                assemblyName: string.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N")),
                syntaxTrees: new[] { CSharpSyntaxTree.ParseText(sourceCode) },
                references: this.GetMetadataReferences().Value,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                var result = compilation.Emit(ms);

                if (!result.Success)
                {
                    return(() => new NancyRazorErrorView(BuildErrorMessage(result, viewLocationResult, sourceCode), this.traceConfiguration));
                }

                ms.Seek(0, SeekOrigin.Begin);
                var viewAssembly = Assembly.Load(ms.ToArray());

                return(() => (INancyRazorView)Activator.CreateInstance(viewAssembly.GetType("RazorOutput.RazorView")));
            }
        }
Esempio n. 15
0
        private Func <INancyRazorView> GetCompiledViewFactory(TextReader reader, Type passedModelType, ViewLocationResult viewLocationResult)
        {
            var engine = new RazorTemplateEngine(this.viewRenderer.Host);

            var razorResult = engine.GenerateCode(reader, null, null, "roo");

            var viewFactory = this.GenerateRazorViewFactory(this.viewRenderer, razorResult, passedModelType, viewLocationResult);

            return(viewFactory);
        }
Esempio n. 16
0
        /// <summary>
        /// Renders the view.
        /// </summary>
        /// <param name="viewLocationResult">A <see cref="ViewLocationResult"/> instance, containing information on how to get the view template.</param>
        /// <param name="model">The model that should be passed into the view</param>
        /// <param name="renderContext">The render context.</param>
        /// <returns>A response.</returns>
        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            Assembly referencingAssembly = null;

            if (model != null)
            {
                var underlyingSystemType = model.GetType().UnderlyingSystemType;
                if (underlyingSystemType != null)
                {
                    referencingAssembly = Assembly.GetAssembly(underlyingSystemType);
                }
            }

            var response = new HtmlResponse();

            response.Contents = stream =>
            {
                var writer =
                    new StreamWriter(stream);

                var view =
                    this.GetViewInstance(viewLocationResult, renderContext, referencingAssembly, model);

                view.ExecuteView(null, null);

                var body = view.Body;
                var sectionContents = view.SectionContents;

                var layout = view.HasLayout ?
                    view.Layout :
                    GetViewStartLayout(model, renderContext, referencingAssembly);

                var root =
                    string.IsNullOrWhiteSpace(layout);

                while (!root)
                {
                    var innerLocationResult = viewLocationResult;

                    viewLocationResult = renderContext.LocateView(layout, model);

                    if (viewLocationResult == null)
                    {
                        throw new RazorLayoutNotFoundException(layout, innerLocationResult);
                    }

                    view = this.GetViewInstance(viewLocationResult, renderContext, referencingAssembly, model);
                    view.ExecuteView(body, sectionContents);

                    body = view.Body;
                    sectionContents = view.SectionContents;

                    layout = view.HasLayout ?
                        view.Layout :
                        GetViewStartLayout(model, renderContext, referencingAssembly);

                    root = !view.HasLayout;
                }

                writer.Write(body);
                writer.Flush();
            };

            return response;
        }
Esempio n. 17
0
        private NancyRazorViewBase GetOrCompileView(ViewLocationResult viewLocationResult, IRenderContext renderContext, Assembly referencingAssembly, Type passedModelType)
        {
            var viewFactory = renderContext.ViewCache.GetOrAdd(
                viewLocationResult,
                x => this.GetCompiledViewFactory(x.Extension, x.Contents.Invoke(), referencingAssembly, passedModelType));

            var view = viewFactory.Invoke();

            view.Code = string.Empty;

            return view;
        }
Esempio n. 18
0
        private Func <INancyRazorView> GetCompiledViewFactory(string extension, TextReader reader, Assembly referencingAssembly, Type passedModelType, ViewLocationResult viewLocationResult)
        {
            var renderer = this.viewRenderers.First(x => x.Extension.Equals(extension, StringComparison.OrdinalIgnoreCase));

            var engine = new RazorTemplateEngine(renderer.Host);

            var razorResult = engine.GenerateCode(reader, null, null, "roo");

            var viewFactory = this.GenerateRazorViewFactory(renderer, razorResult, referencingAssembly, passedModelType, viewLocationResult);

            return(viewFactory);
        }
Esempio n. 19
0
        private static string[] GetViewBodyLines(ViewLocationResult viewLocationResult)
        {
            var templateLines = new List<string>();
            using (var templateReader = viewLocationResult.Contents.Invoke())
            {
                var currentLine = templateReader.ReadLine();
                while (currentLine != null)
                {
                    templateLines.Add(Helpers.HttpUtility.HtmlEncode(currentLine));

                    currentLine = templateReader.ReadLine();
                }
            }
            return templateLines.ToArray();
        }
Esempio n. 20
0
 /// <summary>
 /// Renders the view.
 /// </summary>
 /// <param name="viewLocationResult">A <see cref="ViewLocationResult"/> instance, containing information on how to get the view template.</param>
 /// <param name="model">The model that should be passed into the view</param>
 /// <param name="renderContext">The render context.</param>
 /// <returns>A response.</returns>
 public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
 {
     return(RenderView(viewLocationResult, model, renderContext, false));
 }
Esempio n. 21
0
        private Func<INancyRazorView> GetCompiledViewFactory(string extension, TextReader reader, Assembly referencingAssembly, Type passedModelType, ViewLocationResult viewLocationResult)
        {
            var renderer = this.viewRenderers.First(x => x.Extension.Equals(extension, StringComparison.OrdinalIgnoreCase));

            var engine = new RazorTemplateEngine(renderer.Host);

            var razorResult = engine.GenerateCode(reader, null, null, "roo");

            var viewFactory = this.GenerateRazorViewFactory(renderer, razorResult, referencingAssembly, passedModelType, viewLocationResult);

            return viewFactory;
        }
Esempio n. 22
0
        private Func <NancyRazorViewBase> GetCompiledViewFactory(string extension, TextReader reader, Assembly referencingAssembly, Type passedModelType, ViewLocationResult viewLocationResult)
        {
            var renderer = this.viewRenderers.First(x => x.Extension.Equals(extension, StringComparison.OrdinalIgnoreCase));

            var engine = this.GetRazorTemplateEngine(renderer.Host);

            var razorResult = engine.GenerateCode(reader, sourceFileName: "placeholder");

            var viewFactory = this.GenerateRazorViewFactory(renderer.Provider, razorResult, referencingAssembly, renderer.Assemblies, passedModelType, viewLocationResult);

            return(viewFactory);
        }
Esempio n. 23
0
        private INancyRazorView GetViewInstance(ViewLocationResult viewLocationResult, IRenderContext renderContext, Assembly referencingAssembly, dynamic model)
        {
            var modelType = (model == null) ? typeof(object) : model.GetType();

            var view =
                this.GetOrCompileView(viewLocationResult, renderContext, referencingAssembly, modelType);

            view.Initialize(this, renderContext, model);

            return view;
        }
Esempio n. 24
0
        private Func <NancyRazorViewBase> GenerateRazorViewFactory(CodeDomProvider codeProvider, GeneratorResults razorResult, Assembly referencingAssembly, IEnumerable <string> rendererSpecificAssemblies, Type passedModelType, ViewLocationResult viewLocationResult)
        {
            var outputAssemblyName = Path.Combine(Path.GetTempPath(), String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N")));

            var modelType = FindModelType(razorResult.Document, passedModelType);

            var assemblies = new List <string>
            {
                GetAssemblyPath(typeof(System.Runtime.CompilerServices.CallSite)),
                GetAssemblyPath(typeof(IHtmlString)),
                GetAssemblyPath(Assembly.GetExecutingAssembly()),
                GetAssemblyPath(modelType)
            };

            if (referencingAssembly != null)
            {
                assemblies.Add(GetAssemblyPath(referencingAssembly));
            }

            assemblies = assemblies
                         .Union(rendererSpecificAssemblies)
                         .ToList();

            if (this.razorConfiguration != null)
            {
                var assemblyNames = this.razorConfiguration.GetAssemblyNames();
                if (assemblyNames != null)
                {
                    assemblies.AddRange(assemblyNames.Select(Assembly.Load).Select(GetAssemblyPath));
                }

                if (this.razorConfiguration.AutoIncludeModelNamespace)
                {
                    AddModelNamespace(razorResult, modelType);
                }
            }

            var compilerParameters = new CompilerParameters(assemblies.ToArray(), outputAssemblyName);

            CompilerResults results;

            lock (this.compileLock)
            {
                results = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode);
            }

            if (results.Errors.HasErrors)
            {
                var fullTemplateName = viewLocationResult.Location + "/" + viewLocationResult.Name + "." + viewLocationResult.Extension;
                var templateLines    = GetViewBodyLines(viewLocationResult);
                var errors           = results.Errors.OfType <CompilerError>().Where(ce => !ce.IsWarning).ToArray();
                var errorMessages    = BuildErrorMessages(errors);

                MarkErrorLines(errors, templateLines);

                var errorDetails = string.Format(
                    "Error compiling template: <strong>{0}</strong><br/><br/>Errors:<br/>{1}<br/><br/>Details:<br/>{2}",
                    fullTemplateName,
                    errorMessages,
                    templateLines.Aggregate((s1, s2) => s1 + "<br/>" + s2));

                return(() => new NancyRazorErrorView(errorDetails));
            }

            var assembly = Assembly.LoadFrom(outputAssemblyName);

            if (assembly == null)
            {
                const string error = "Error loading template assembly";
                return(() => new NancyRazorErrorView(error));
            }

            var type = assembly.GetType("RazorOutput.RazorView");

            if (type == null)
            {
                var error = String.Format("Could not find type RazorOutput.Template in assembly {0}", assembly.FullName);
                return(() => new NancyRazorErrorView(error));
            }

            if (Activator.CreateInstance(type) as NancyRazorViewBase == null)
            {
                const string error = "Could not construct RazorOutput.Template or it does not inherit from RazorViewBase";
                return(() => new NancyRazorErrorView(error));
            }

            return(() => (NancyRazorViewBase)Activator.CreateInstance(type));
        }