public static Template GetTemplateFromFile(ViewLocationResult path)
 {
     // can't cache anything here since template depends on current context
     var contents = path.Contents;
     var template = Template.Parse(contents);
     return template;
 }
Example #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"></param>
        /// <returns>A delegate that can be invoked with the <see cref="Stream"/> that the view should be rendered to.</returns>
        public Action<Stream> RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            return stream =>{

                var templateManagerProvider =
                    new TemplateManagerProvider()
                        .WithLoader(new TemplateLoader(viewLocationResult.Contents.Invoke()));

                var templateManager =
                    templateManagerProvider.GetNewManager();

                var template = renderContext.ViewCache.GetOrAdd(
                    viewLocationResult,
                    x => templateManager.GetTemplate(string.Empty));

                var context = new Dictionary<string, object> { { "Model", model } };
                var reader = template.Walk(templateManager, context);

                var writer =
                    new StreamWriter(stream);

                writer.Write(reader.ReadToEnd());
                writer.Flush();
            };
        }
Example #3
0
        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            var template = renderContext.ViewCache.GetOrAdd(viewLocationResult, result =>
            {
                try
                {
                    var context = new NancyVeilContext(renderContext, Extensions);
                    var engine = new VeilEngine(context);
                    Type modelType = model == null ? typeof(object) : model.GetType();
                    return engine.CompileNonGeneric(viewLocationResult.Extension, result.Contents(), modelType);
                }
                catch (Exception e)
                {
                    return CreateErrorPage(e);
                }
            });

            var response = new HtmlResponse();
            response.ContentType = "text/html; charset=utf-8";
            response.Contents = s =>
            {
                var writer = new StreamWriter(s, Encoding.UTF8);
                template(writer, model);
                writer.Flush();
            };
            return response;
        }
        public void Include_should_look_for_a_partial()
        {
            // Set up the view startup context
            string partialPath = Path.Combine(Environment.CurrentDirectory, @"TestViews\_partial.liquid");

            // Set up a ViewLocationResult that the test can use
            var testLocation = new ViewLocationResult(
                Environment.CurrentDirectory,
                "test",
                "liquid",
                () => new StringReader(@"<h1>Including a partial</h1>{% include 'partial' %}")
            );

            var partialLocation = new ViewLocationResult(
                partialPath,
                "partial",
                "liquid",
                () => new StringReader(File.ReadAllText(partialPath))
            );

            var currentStartupContext = CreateContext(new [] {testLocation, partialLocation});

            this.engine = new DotLiquidViewEngine(new LiquidNancyFileSystem(currentStartupContext));

            // Given
            var stream = new MemoryStream();

            // When
            var response = this.engine.RenderView(testLocation, null, this.renderContext);
            response.Contents.Invoke(stream);

            // Then
            stream.ShouldEqual("<h1>Including a partial</h1>Some template.");
        }
        public void Should_be_able_to_render_view_with_partial_to_stream()
        {
            // Given
            var location = new ViewLocationResult(
                string.Empty,
                string.Empty,
                "cshtml",
                () => new StringReader(@"@{var x = ""test"";}<h1>Hello Mr. @x</h1> @Html.Partial(""partial.cshtml"")")
            );

            var partialLocation = new ViewLocationResult(
                string.Empty,
                "partial.cshtml",
                "cshtml",
                () => new StringReader(@"this is partial")
            );

            A.CallTo(() => this.renderContext.LocateView("partial.cshtml",null)).Returns(partialLocation);

            var stream = new MemoryStream();

            // When
            var response = this.engine.RenderView(location, null,this.renderContext);
            response.Contents.Invoke(stream);

            // Then
            stream.ShouldEqual("<h1>Hello Mr. test</h1> this is partial");
        }
        public void Should_return_Markdown()
        {
            // Given
            const string markdown = @"#Header1
##Header2
###Header3
Hi there!
> This is a blockquote.";

            var location = new ViewLocationResult(
                string.Empty,
                string.Empty,
                "md",
                () => new StringReader(markdown)
            );

            var html = this.viewEngine.ConvertMarkdown(location);

            var stream = new MemoryStream();

            A.CallTo(() => this.renderContext.ViewCache.GetOrAdd(location, A<Func<ViewLocationResult, string>>.Ignored))
             .Returns(html);

            // When
            var response = this.viewEngine.RenderView(location, null, this.renderContext);
            response.Contents.Invoke(stream);

            // Then
            var result = ReadAll(stream);
            result.ShouldEqual(html);
        }
        public virtual IDictionary<string, object> GetExtraParameters(ViewLocationResult viewLocationResult)
        {
            var extra = new Dictionary<string, object>();
            foreach (var filter in Filters)
            {
                filter.ExtraParameters(viewLocationResult, extra);
            }

            return extra;
        }
        /// <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>
        /// <returns>A response.</returns>
        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            return new HtmlResponse(contents: s =>
                {
                    var writer = new StreamWriter(s);
                    var templateContents = renderContext.ViewCache.GetOrAdd(viewLocationResult, vr => vr.Contents.Invoke().ReadToEnd());

                    writer.Write(this.viewEngine.Render(templateContents, model, new NancyViewEngineHost(renderContext)));
                    writer.Flush();
                });
        }
 public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
 {
     System.Diagnostics.Debug.WriteLine("test");
     return new HtmlResponse(
         contents: stream =>
         {
             var templateFactory = renderContext.ViewCache.GetOrAdd(
                 viewLocationResult, x => GetTemplateFactory(viewLocationResult));
             RenderTemplateFromTemplateFactory(templateFactory, stream, model, renderContext.Context);
         }
     );
 }
        /// <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>
        /// <returns>A delegate that can be invoked with the <see cref="Stream"/> that the view should be rendered to.</returns>
        public Action<Stream> RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            Interlocked.CompareExchange(ref this.viewEngine, new SuperSimpleViewEngine(new NancyViewEngineHost(renderContext)), null);

            return s =>
            {
                var writer = new StreamWriter(s);
                var templateContents = renderContext.ViewCache.GetOrAdd(viewLocationResult, vr => vr.Contents.Invoke().ReadToEnd());

                writer.Write(this.viewEngine.Render(templateContents, model));
                writer.Flush();
            };
        }
Example #11
0
        /// <summary>
        /// Converts the markdown.
        /// </summary>
        /// <returns>
        /// HTML converted from markdown
        /// </returns>
        /// <param name='viewLocationResult'>
        /// View location result.
        /// </param>
        public string ConvertMarkdown(ViewLocationResult viewLocationResult)
        {
            string content =
                viewLocationResult.Contents().ReadToEnd();

            if (content.StartsWith("<!DOCTYPE html>"))
            {
                return MarkdownViewengineRender.RenderMasterPage(content);
            }

            var parser = new Markdown();
            var html = parser.Transform(content);
            return ParagraphSubstitution.Replace(html, "$1");
        }
        /// <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 to be passed into the view</param>
        /// <param name="renderContext"></param>
        /// <returns>A response</returns>
        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            return new HtmlResponse
            {
                Contents = stream =>
                {
                    var templateName = viewLocationResult.Name;

                    var handlebars = threadLocalHandlebars.Value;
                    handlebars.RegisterTemplate(templateName, () =>
                    {
                        using (var textReader = viewLocationResult.Contents())
                        {
                            return textReader.ReadToEnd();
                        }

                    });
                    foreach (var partial in viewLocator.GetAllCurrentlyDiscoveredViews().Where(x => x.Name.StartsWith("_")))
                    {
                        var partialName = partial.Name.TrimStart('_');
                        handlebars.RegisterPartial(partialName, () =>
                        {
                            using (var textReader = partial.Contents())
                            {
                                return textReader.ReadToEnd();
                            }
                        });
                    }
                    using (var writer = new StreamWriter(stream))
                    {
                        dynamic output;
                        try
                        {
                            output = handlebars.Transform(templateName, model);
                        }
                        catch (Exception)
                        {
                            //TODO: remove this exception handling after a few versions
                            var templateContents = viewLocationResult.Contents().ReadToEnd();
                            if (templateContents.Contains("{{> _") || templateContents.Contains("{{>_"))
                            {
                                throw new Exception(string.Format("Template '{0}' contains and underscore prefixed partial name. This is no longer required. Search for the string '{{>_' or '{{> _' in your template and remove the '_'.", templateName));
                            }
                            throw;
                        }
                        writer.Write(output);
                    }
                }
            };
        }
        public void Render_should_create_valid_nhaml_IViewSource()
        {
            // Given
            var textReader = new StringReader("Hello world");
            var viewLocationResult = new ViewLocationResult("folder", "file", "haml", () => textReader);

            // When
            var template = engine.RenderView(viewLocationResult, null, this.renderContext);
            template.Contents.Invoke(new MemoryStream());

            // Then
            A.CallTo(() => nHamlEngine.GetCompiledTemplate(
                A<NancyNHamlView>.That.Matches(x => x.FilePath == @"folder\file.haml" && x.GetTextReader() == textReader),
                A<Type>.Ignored)).MustHaveHappened();
        }
        public void RenderViewSetsPath()
        {
            // arrange
            var templateLocator = A.Fake<IViewLocator>();
            var viewCompiler = A.Fake<IViewCompiler>();
            var viewLocationResult = new ViewLocationResult(@"c:\some\fake\path", null);
            A.CallTo(() => templateLocator.GetTemplateContents("test")).Returns(viewLocationResult);
            var engine = new RazorViewEngine(templateLocator, viewCompiler);

            // act
            var result = engine.RenderView("test", null);

            // assert
            result.Location.ShouldEqual(@"c:\some\fake\path");
        }
Example #15
0
        public DotLiquidView(ControllerContext controllerContext, IViewLocator locator, ViewLocationResult viewResult, ViewLocationResult masterViewResult)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            if (viewResult == null)
            {
                throw new ArgumentNullException("viewPath");
            }

            _locator = locator;
            this.ViewResult = viewResult;
            this.MasterViewResult = masterViewResult;
        }
Example #16
0
        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            //we already have a view but we still need a view provider
            return new HtmlResponse(contents: stream =>
                {
                    var host = new NancyParrotHost(_modelValueProviderFactory, new NancyPathResolver(renderContext));
                    var parrotWriter = host.CreateWriter();
                    var rendererFactory = host.RendererFactory;
                    var view = new ParrotView(host, rendererFactory, _parrotViewLocator, viewLocationResult.Contents, parrotWriter);
                    var writer = new StreamWriter(stream);
                    
                    view.Render(model, writer);

                    writer.Flush();
                });
        }
Example #17
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"></param>
        /// <returns>A delegate that can be invoked with the <see cref="Stream"/> that the view should be rendered to.</returns>
        public Action<Stream> RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            return stream =>{
                var provider = new TemplateManagerProvider().WithLoader(new TemplateLoader(renderContext, viewLocationResult));

                var templateManager = provider.GetNewManager();

                var context = new Dictionary<string, object> { { "Model", model } };

                var reader = templateManager.GetTemplate(viewLocationResult.Location).Walk(templateManager, context);

                var writer = new StreamWriter(stream);

                writer.Write(reader.ReadToEnd());
                writer.Flush();
            };
        }
        public void GetCompiledView_should_render_to_stream()
        {
            // Given
            var location = new ViewLocationResult(
                string.Empty,
                "cshtml",
                new StringReader(@"@{var x = ""test"";}<h1>Hello Mr. @x</h1>")
            );

            var stream = new MemoryStream();

            // When
            var action = this.engine.RenderView(location, null);
            action.Invoke(stream);

            // Then
            stream.ShouldEqual("<h1>Hello Mr. test</h1>");
        }
        public void GetCompiledView_should_render_to_stream()
        {
            // Given
            var location = new ViewLocationResult(
                string.Empty,
                "django",
                new StringReader(@"{% ifequal a a %}<h1>Hello Mr. test</h1>{% endifequal %}")
            );

            var stream = new MemoryStream();

            // When
            var action = engine.RenderView(location, null);
            action.Invoke(stream);

            // Then
            stream.ShouldEqual("<h1>Hello Mr. test</h1>");
        }
        public void RenderViewShouldReturnCompiledView()
        {
            // arrange
            var templateLocator = A.Fake<IViewLocator>();
            var viewCompiler = A.Fake<IViewCompiler>();
            var view = A.Fake<IView>();
            var viewLocationResult = new ViewLocationResult(@"c:\some\fake\path", null);
            A.CallTo(() => templateLocator.GetTemplateContents("test")).Returns(viewLocationResult);
            A.CallTo(() => viewCompiler.GetCompiledView(null)).Returns(view);
            var engine = new RazorViewEngine(templateLocator, viewCompiler);
            var stream = new MemoryStream();

            // act
            var result = engine.RenderView("test", stream);

            // assert
            result.View.ShouldBeSameAs(view);
        }
Example #21
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"></param>
        /// <returns>A response</returns>
        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            return new HtmlResponse(contents: stream =>
            {
                var provider = new TemplateManagerProvider().WithLoader(new TemplateLoader(renderContext, viewLocationResult));

                var templateManager = provider.GetNewManager();

                var context = new Dictionary<string, object> { { "Model", UnwrapDictionary(model) } };

                var reader = templateManager.GetTemplate(viewLocationResult.Location).Walk(templateManager, context);

                var writer = new StreamWriter(stream, Encoding.UTF8);

                writer.Write(reader.ReadToEnd());
                writer.Flush();
            });
        }
        public void Include_should_look_for_a_partial()
        {
            // Given
            var location = new ViewLocationResult(
                string.Empty,
                string.Empty,
                "liquid",
                () => new StringReader(@"<h1>Including a partial</h1>{% include 'partial' %}")
            );

            var stream = new MemoryStream();

            // When
            var response = this.engine.RenderView(location, null, this.renderContext);
            response.Contents.Invoke(stream);

            // Then
            stream.ShouldEqual("<h1>Including a partial</h1>Some template.");
        }
        /// <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"></param>
        /// <returns>A response</returns>
        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            return new HtmlResponse(contents: stream =>
            {
                var hashedModel =
                    Hash.FromAnonymousObject(new { model = new DynamicDrop(model) });

                var parsed = renderContext.ViewCache.GetOrAdd(
                    viewLocationResult,
                    x => Template.Parse(viewLocationResult.Contents.Invoke().ReadToEnd()));

                var rendered = parsed.Render(hashedModel);

                var writer = new StreamWriter(stream);

                writer.Write(rendered);
                writer.Flush();
            });
        }
        public void GetCompiledView_should_render_to_stream()
        {
            // Given
            var location = new ViewLocationResult(
                string.Empty,
                string.Empty,
                "django",
                () => new StringReader(@"{% ifequal a a %}<h1>Hello Mr. test</h1>{% endifequal %}")
            );
            A.CallTo(() => this.renderContext.LocateView(".django", null)).Returns(location);

            var stream = new MemoryStream();

            // When
            var action = engine.RenderView(location, null, this.renderContext);
            action.Invoke(stream);

            // Then
            stream.ShouldEqual("<h1>Hello Mr. test</h1>");
        }
Example #25
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)
        {
            var response = new HtmlResponse();

            var html = renderContext.ViewCache.GetOrAdd(viewLocationResult, result =>
                                                                                {
                                                                                    return ConvertMarkdown(viewLocationResult);
                                                                                });



            var renderHtml = this.engineWrapper.Render(html, model, new MarkdownViewEngineHost(new NancyViewEngineHost(renderContext), renderContext, this.Extensions));

            response.Contents = stream =>
            {
                var writer = new StreamWriter(stream);
                writer.Write(renderHtml);
                writer.Flush();
            };

            return response;
        }
        public void Should_transfer_anonymoustype_model_members_to_expandoobject_members_before_invoking_view_engines()
        {
            // Given
            var viewEngines = new[] {
                new FakeViewEngine {
                    Extensions = new[] { "html" }
                }
            };

            var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());

            A.CallTo(() => this.resolver.GetViewLocation(A <string> .Ignored, A <object> .Ignored, A <ViewLocationContext> .Ignored)).Returns(location);

            var model   = new { Name = "Nancy" };
            var factory = this.CreateFactory(viewEngines);

            // When
            factory.RenderView("foo", model, new ViewLocationContext());

            // Then
            ((string)viewEngines[0].Model.Name).ShouldEqual("Nancy");
        }
Example #27
0
        public static Template GetTemplateFromFile(ViewLocationResult path)
        {
            var contextKey = "vc-cms-file-" + path.Location;
            /*
            var value = HttpRuntime.Cache.Get(contextKey);

            if (value != null)
            {
                return value as Template;
            }
             * */

            if (path.Contents == null)
                return null;

            var contents = path.Contents.Invoke().ReadToEnd();
            var template = Template.Parse(contents);

            //HttpRuntime.Cache.Insert(contextKey, template, new CacheDependency(new[] { path.Location}));

            return template;
        }
Example #28
0
        public void return_viewlocationresult_when_view_could_be_located()
        {
            // Given
            const string viewName = "foo.html";

            var resolver = new DefaultViewResolver(
                this.viewLocator,
                new ViewLocationConventions(new Func <string, dynamic, ViewLocationContext, string>[] {
                (name, model, path) => "bar.html"
            }));

            var locatedView =
                new ViewLocationResult("name", "location", "extension", GetEmptyContentReader());

            A.CallTo(() => this.viewLocator.LocateView(A <string> .Ignored, A <NancyContext> .Ignored)).Returns(locatedView);

            // When
            var result = resolver.GetViewLocation(viewName, null, this.viewLocationContext);

            // Then
            result.ShouldBeSameAs(locatedView);
        }
Example #29
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)
        {
            var response = new HtmlResponse();

            var html = renderContext.ViewCache.GetOrAdd(viewLocationResult, result =>
            {
                return(ConvertMarkdown(viewLocationResult));
            });



            var renderHtml = this.engineWrapper.Render(html, model, new MarkdownViewEngineHost(new NancyViewEngineHost(renderContext), renderContext, this.Extensions));

            response.Contents = stream =>
            {
                var writer = new StreamWriter(stream);
                writer.Write(renderHtml);
                writer.Flush();
            };

            return(response);
        }
Example #30
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"></param>
        /// <returns>A response</returns>
        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            return new HtmlResponse(contents: stream =>
            {
                var hashedModel =
                    Hash.FromAnonymousObject(new
                        {
                            Model = new DynamicDrop(model),
                            ViewBag = new DynamicDrop(renderContext.Context.ViewBag)
                        });

                var parsed = renderContext.ViewCache.GetOrAdd(
                    viewLocationResult,
                    x => Template.Parse(viewLocationResult.Contents.Invoke().ReadToEnd()));

                parsed.Render(stream, new RenderParameters
                    {
                        LocalVariables = hashedModel,
                        Registers = Hash.FromAnonymousObject(new { nancy = renderContext })
                    });
            });
        }
Example #31
0
        public void RenderView_should_accept_a_model_and_read_from_it_into_the_stream()
        {
            // Given
            var location = new ViewLocationResult(
                string.Empty,
                string.Empty,
                "cshtml",
                () => new StringReader(@"<h1>Hello Mr. @Model.Name</h1>")
            );

            var stream = new MemoryStream();

            dynamic model = new ExpandoObject();
            model.Name = "test";

            // When
            var response = this.engine.RenderView(location, model, this.renderContext);
            response.Contents.Invoke(stream);

            // Then
            stream.ShouldEqual("<h1>Hello Mr. test</h1>");
        }
Example #32
0
        public void GetCompiledView_should_render_to_stream()
        {
            // Given
            var location = new ViewLocationResult(
                string.Empty,
                string.Empty,
                "django",
                () => new StringReader(@"{% ifequal a a %}<h1>Hello Mr. test</h1>{% endifequal %}")
                );

            A.CallTo(() => this.renderContext.LocateView(".django", null)).Returns(location);

            var stream = new MemoryStream();

            // When
            var response = engine.RenderView(location, null, this.renderContext);

            response.Contents.Invoke(stream);

            // Then
            stream.ShouldEqual("<h1>Hello Mr. test</h1>");
        }
Example #33
0
        private SparkViewEngineResult LocateView(string viewPath, string viewName, ViewLocationResult viewLocationResult, IRenderContext renderContext)
        {
            var searchedLocations = new List <string>();

            var descriptorParams = new BuildDescriptorParams(viewPath, viewName, null, true, null);

            var descriptor = this.descriptorBuilder.BuildDescriptor(
                descriptorParams,
                searchedLocations);

            if (descriptor == null)
            {
                return(new SparkViewEngineResult(searchedLocations));
            }

            var entry = renderContext.ViewCache.GetOrAdd(
                viewLocationResult,
                x => this.engine.CreateEntry(descriptor));

            return(new SparkViewEngineResult(
                       entry.CreateInstance() as NancySparkView));
        }
        public void Should_covert_anonymoustype_model_to_expandoobject_before_invoking_view_engine()
        {
            // Given
            var viewEngines = new[] {
                A.Fake <IViewEngine>(),
            };

            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });

            var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());

            A.CallTo(() => this.resolver.GetViewLocation(A <string> .Ignored, A <object> .Ignored, A <ViewLocationContext> .Ignored)).Returns(location);

            var model   = new { Name = "" };
            var factory = this.CreateFactory(viewEngines);

            // When
            factory.RenderView("foo", model, new ViewLocationContext());

            // Then
            A.CallTo(() => viewEngines[0].RenderView(A <ViewLocationResult> .Ignored, A <object> .That.Matches(x => x.GetType().Equals(typeof(ExpandoObject))), A <IRenderContext> .Ignored)).MustHaveHappened();
        }
Example #35
0
        public void RenderView_should_accept_a_model_and_read_from_it_into_the_stream()
        {
            // Given
            var location = new ViewLocationResult(
                string.Empty,
                string.Empty,
                "liquid",
                () => new StringReader(@"<h1>Hello Mr. {{ model.name }}</h1>")
            );

            var currentStartupContext =
                CreateContext(new [] {location});

            this.engine.Initialize(currentStartupContext);
            var stream = new MemoryStream();

            // When
            var response = this.engine.RenderView(location, new { name = "test" }, this.renderContext);
            response.Contents.Invoke(stream);

            // Then
            stream.ShouldEqual("<h1>Hello Mr. test</h1>");
        }
        public void RenderView_should_accept_a_model_with_a_list_and_iterate_over_it()
        {
            // Given
            var location = new ViewLocationResult(
                string.Empty,
                string.Empty,
                "liquid",
                () => new StringReader(@"<ul>{% for item in model.Widgets %}<li>{{ item.name }}</li>{% endfor %}</ul>")
                );

            var stream = new MemoryStream();

            // When
            var widgets = new List <object> {
                new { name = "Widget 1" }, new { name = "Widget 2" }, new { name = "Widget 3" }, new { name = "Widget 4" }
            };
            var action = this.engine.RenderView(location, new { Widgets = widgets }, this.renderContext);

            action.Invoke(stream);

            // Then
            stream.ShouldEqual("<ul><li>Widget 1</li><li>Widget 2</li><li>Widget 3</li><li>Widget 4</li></ul>");
        }
Example #37
0
        private void FindViewAndRender <T>(string viewName, T viewModel) where T : class
        {
            var location           = Path.Combine("Stub", viewName + ".spark");
            var viewLocationResult = new ViewLocationResult(location, viewName, "spark", GetEmptyContentReader());
            var stream             = new MemoryStream();
            var engine             = new SparkViewEngine();

            var context = new ViewEngineStartupContext(
                A.Fake <IViewCache>(),
                this.fileSystemViewLocationProvider.GetLocatedViews(new[] { "spark" }));

            engine.Initialize(context);

            //When
            var action = engine.RenderView(viewLocationResult, viewModel, this.renderContext);

            action.Invoke(stream);
            stream.Position = 0;
            using (var reader = new StreamReader(stream))
            {
                this.output = reader.ReadToEnd();
            }
        }
        public void Should_call_first_view_engine_that_supports_extension_with_view_location_results()
        {
            // Given
            var viewEngines = new[] {
                A.Fake <IViewEngine>(),
                A.Fake <IViewEngine>(),
            };

            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
            A.CallTo(() => viewEngines[1].Extensions).Returns(new[] { "html" });

            var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());

            A.CallTo(() => this.resolver.GetViewLocation(A <string> .Ignored, A <object> .Ignored, A <ViewLocationContext> .Ignored)).Returns(location);

            var factory = this.CreateFactory(viewEngines);

            // When
            factory.RenderView("foo", null, this.viewLocationContext);

            // Then
            A.CallTo(() => viewEngines[0].RenderView(location, null, A <IRenderContext> .Ignored)).MustHaveHappened();
        }
Example #39
0
        public void Should_invoke_view_engine_with_model()
        {
            // Given
            var viewEngines = new[] {
                A.Fake <IViewEngine>(),
            };

            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
            A.CallTo(() => viewEngines[0].RenderView(A <ViewLocationResult> .Ignored, null)).Throws(new Exception());

            var location = new ViewLocationResult(string.Empty, "html", null);

            A.CallTo(() => this.locator.GetViewLocation("foo", A <IEnumerable <string> > .Ignored)).Returns(location);

            var model   = new object();
            var factory = this.CreateFactory(viewEngines);

            // When
            var action = factory["foo", model];

            // Then
            A.CallTo(() => viewEngines[0].RenderView(A <ViewLocationResult> .Ignored, model)).MustHaveHappened();
        }
        public void Should_invoke_view_engine_with_model()
        {
            // Given
            var viewEngines = new[] {
                A.Fake <IViewEngine>(),
            };

            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
            A.CallTo(() => viewEngines[0].RenderView(A <ViewLocationResult> .Ignored, null, null)).Throws(new Exception());

            var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());

            A.CallTo(() => this.resolver.GetViewLocation(A <string> .Ignored, A <object> .Ignored, A <ViewLocationContext> .Ignored)).Returns(location);

            var model   = new object();
            var factory = this.CreateFactory(viewEngines);

            // When
            factory.RenderView("foo", model, this.viewLocationContext);

            // Then
            A.CallTo(() => viewEngines[0].RenderView(A <ViewLocationResult> .Ignored, model, A <IRenderContext> .Ignored)).MustHaveHappened();
        }
Example #41
0
        public void Should_call_first_view_engine_that_supports_extension_with_view_location_results()
        {
            // Given
            var viewEngines = new[] {
                A.Fake <IViewEngine>(),
                A.Fake <IViewEngine>(),
            };

            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
            A.CallTo(() => viewEngines[1].Extensions).Returns(new[] { "html" });

            var location = new ViewLocationResult(string.Empty, "html", null);

            A.CallTo(() => this.locator.GetViewLocation("foo", A <IEnumerable <string> > .Ignored)).Returns(location);

            var factory = this.CreateFactory(viewEngines);

            // When
            var action = factory["foo"];

            // Then
            A.CallTo(() => viewEngines[0].RenderView(location, null)).MustHaveHappened();
        }
Example #42
0
        public void Should_return_action_from_invoked_engine()
        {
            // Given
            var viewEngines = new[] {
                A.Fake <IViewEngine>(),
            };

            Action <Stream> actionReturnedFromEngine = x => { };

            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
            A.CallTo(() => viewEngines[0].RenderView(A <ViewLocationResult> .Ignored, null)).Returns(actionReturnedFromEngine);

            var location = new ViewLocationResult(string.Empty, "html", null);

            A.CallTo(() => this.locator.GetViewLocation("foo", A <IEnumerable <string> > .Ignored)).Returns(location);

            var factory = this.CreateFactory(viewEngines);

            // When
            var action = factory["foo"];

            // Then
            action.ShouldEqual(actionReturnedFromEngine);
        }
Example #43
0
        private string ExecuteView(ViewLocationResult viewLocationResult, dynamic model)
        {
            //Preprocess the location result and inject the global helper
            TextReader processedContentStream = InjectHelpersToView(viewLocationResult.Contents);

            var      cache = System.Runtime.Caching.MemoryCache.Default;
            ViewBase view  = (ViewBase)cache.Get(viewLocationResult.Location);

            if (view == null)
            {
                view = GetCompiledView <dynamic>(processedContentStream);
                var cachePolicy = new CacheItemPolicy();
                cachePolicy.ChangeMonitors.Add(new HostFileChangeMonitor(new List <string> {
                    viewLocationResult.Location
                }));
                cache.Add(new System.Runtime.Caching.CacheItem(viewLocationResult.Location, view), cachePolicy);
            }

            view.Global = _modelProvider.GetGlobalModel();
            view.Model  = model ?? _modelProvider.GetModel(Path.GetFileNameWithoutExtension(viewLocationResult.Location));

            view.RenderPartialImpl = (partialViewName, partialModel)
                                     => new HtmlStringLiteral(ExecuteView(Conventions.PartialsPrefix + partialViewName, partialModel));
            view.Execute();

            if (string.IsNullOrEmpty(view.Layout))
            {
                return(view.GetContents());
            }
            else
            {
                string layout = ExecuteView(String.Format("{0}{1}", Conventions.LayoutsPrefix, view.Layout), model);

                return(layout.Replace("{{content}}", view.GetContents()));
            }
        }
        public void RenderView_should_render_to_stream()
        {
            // Given
            var location = new ViewLocationResult(
                string.Empty,
                string.Empty,
                "liquid",
                () => new StringReader(@"{% assign name = 'test' %}<h1>Hello Mr. {{ name }}</h1>")
            );

            var currentStartupContext =
                this.CreateContext(location);

            this.engine.Initialize(currentStartupContext);

            var stream = new MemoryStream();

            // When
            var response = this.engine.RenderView(location, null, this.renderContext);
            response.Contents.Invoke(stream);

            // Then
            stream.ShouldEqual("<h1>Hello Mr. test</h1>");
        }
Example #45
0
        public void Syntax_errors_should_return_500()
        {
            // Given
            var location = new ViewLocationResult(
                string.Empty,
                string.Empty,
                "liquid",
                () => new StringReader(@"{% if true %}{% end %}")
                );

            var currentStartupContext =
                CreateContext(new[] { location });

            this.engine.Initialize(currentStartupContext);
            var stream = new MemoryStream();

            // When
            var response = this.engine.RenderView(location, null, this.renderContext);

            response.Contents.Invoke(stream);

            // Then
            response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError);
        }
Example #46
0
        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            var template = renderContext.ViewCache.GetOrAdd(viewLocationResult, result =>
            {
                using (var contents = result.Contents())
                {
                    var context    = new NancyVeilContext(renderContext, Extensions);
                    var engine     = new VeilEngine(context);
                    Type modelType = model == null ? typeof(object) : model.GetType();
                    return(engine.CompileNonGeneric(viewLocationResult.Extension, contents, modelType));
                }
            });

            var response = new HtmlResponse();

            response.ContentType = "text/html; charset=utf-8";
            response.Contents    = s =>
            {
                var writer = new StreamWriter(s, Encoding.UTF8);
                template(writer, model);
                writer.Flush();
            };
            return(response);
        }
Example #47
0
        public void Should_return_empty_action_when_view_engine_throws_exception()
        {
            var viewEngines = new[] {
                A.Fake <IViewEngine>(),
            };

            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
            A.CallTo(() => viewEngines[0].RenderView(A <ViewLocationResult> .Ignored, null)).Throws(new Exception());

            var location = new ViewLocationResult(string.Empty, "html", null);

            A.CallTo(() => this.locator.GetViewLocation("foo", A <IEnumerable <string> > .Ignored)).Returns(location);

            var stream  = new MemoryStream();
            var factory = this.CreateFactory(viewEngines);

            // When
            var action = factory["foo"];

            action.Invoke(stream);

            // Then
            stream.Length.ShouldEqual(0L);
        }
        public void Should_return_empty_action_when_view_engine_throws_exception()
        {
            var viewEngines = new[] {
                A.Fake <IViewEngine>(),
            };

            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
            A.CallTo(() => viewEngines[0].RenderView(A <ViewLocationResult> .Ignored, null, A <IRenderContext> .Ignored)).Throws(new Exception());

            var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());

            A.CallTo(() => this.resolver.GetViewLocation(A <string> .Ignored, A <object> .Ignored, A <ViewLocationContext> .Ignored)).Returns(location);

            var stream  = new MemoryStream();
            var factory = this.CreateFactory(viewEngines);

            // When
            var response = factory.RenderView("foo", null, this.viewLocationContext);

            response.Contents.Invoke(stream);

            // Then
            stream.Length.ShouldEqual(0L);
        }
Example #49
0
        public void RenderView_should_accept_a_model_and_read_from_it_into_the_stream()
        {
            // Given
            var location = new ViewLocationResult(
                string.Empty,
                string.Empty,
                "liquid",
                () => new StringReader(@"<h1>Hello Mr. {{ Model.name }}</h1>")
                );

            var currentStartupContext =
                CreateContext(new[] { location });

            this.engine.Initialize(currentStartupContext);
            var stream = new MemoryStream();

            // When
            var response = this.engine.RenderView(location, new { name = "test" }, this.renderContext);

            response.Contents.Invoke(stream);

            // Then
            stream.ShouldEqual("<h1>Hello Mr. test</h1>");
        }
Example #50
0
        public void when_calling_a_missing_member_should_return_an_empty_string()
        {
            // Given
            var location = new ViewLocationResult(
                string.Empty,
                string.Empty,
                "liquid",
                () => new StringReader(@"<h1>Hello Mr. {{ Model.name }}</h1>")
                );

            var currentStartupContext =
                CreateContext(new[] { location });

            this.engine.Initialize(currentStartupContext);
            var stream = new MemoryStream();

            // When
            var response = this.engine.RenderView(location, new { lastname = "test" }, this.renderContext);

            response.Contents.Invoke(stream);

            // Then
            stream.ShouldEqual("<h1>Hello Mr. </h1>");
        }
        public void Should_return_response_from_invoked_engine()
        {
            // Given
            var viewEngines = new[] {
                A.Fake <IViewEngine>(),
            };

            Action <Stream> actionReturnedFromEngine = x => { };

            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
            A.CallTo(() => viewEngines[0].RenderView(A <ViewLocationResult> .Ignored, null, A <IRenderContext> .Ignored)).Returns(actionReturnedFromEngine);

            var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());

            A.CallTo(() => this.resolver.GetViewLocation(A <string> .Ignored, A <object> .Ignored, A <ViewLocationContext> .Ignored)).Returns(location);

            var factory = this.CreateFactory(viewEngines);

            // When
            var response = factory.RenderView("foo", null, this.viewLocationContext);

            // Then
            response.Contents.ShouldBeSameAs(actionReturnedFromEngine);
        }
        public void Render_should_create_use_NancyNHamlTemplate()
        {
            // Given
            var textReader = new StringReader("Hello world");
            var viewLocationResult = new ViewLocationResult("folder", "file", "haml", () => textReader);

            // When
            var template = engine.RenderView(viewLocationResult, null, this.renderContext);
            template.Contents.Invoke(new MemoryStream());

            // Then
            A.CallTo(() => nHamlEngine.GetCompiledTemplate(
                A<NancyNHamlView>.Ignored,
                typeof(NancyNHamlTemplateBase))).MustHaveHappened();
        }
Example #53
0
 public TemplateLoader(IRenderContext renderContext, ViewLocationResult viewLocationResult)
 {
     this.renderContext        = renderContext;
     this.mainTemplateLocation = viewLocationResult;
 }
 public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
 {
     this.Model = model;
     return(new HtmlResponse());
 }
Example #55
0
 private void FindViewAndRender(string viewName, ViewLocationResult viewLocationResult)
 {
     this.FindViewAndRender <dynamic>(viewName, null, viewLocationResult);
 }
Example #56
0
 public ViewLocationModel(ViewLocationResult result)
 {
     this.result = result;
 }
Example #57
0
 public DefaultViewLocatorFixture()
 {
     this.viewLocation      = new ViewLocationResult("location", "view", "html", null);
     this.viewLocationCache = new FakeViewLocationCache(this.viewLocation);
     this.viewLocator       = CreateViewLocator(this.viewLocationCache);
 }
Example #58
0
 public Action <Stream> RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
 {
     this.Model = model;
     return(stream => { });
 }
        /// <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"></param>
        /// <returns>A response</returns>
        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            Template       parsed;
            Hash           hashedModel;
            HttpStatusCode status;

            try
            {
                // Set the parsed template
                parsed = renderContext.ViewCache.GetOrAdd(
                    viewLocationResult,
                    x =>
                {
                    using (var reader = viewLocationResult.Contents.Invoke())
                        return(Template.Parse(reader.ReadToEnd()));
                });

                hashedModel = Hash.FromAnonymousObject(new
                {
                    Model   = new DynamicDrop(model),
                    ViewBag = new DynamicDrop(renderContext.Context.ViewBag)
                });

                // If we got past that, we have a good response
                status = HttpStatusCode.OK;
            }
            catch (SyntaxException syntaxException)
            {
                // Syntax Exceptions cause a 500
                status = HttpStatusCode.InternalServerError;

                // Build the error message
                String errorMessage = String.Format("Syntax error in liquid view '{0}':\r\n\r\n{1}",
                                                    String.Format("{0}/{1}.{2}", viewLocationResult.Location, viewLocationResult.Name, viewLocationResult.Extension),
                                                    syntaxException.Message);

                // Create the error model with a Nancy DynamicDictionary because i can ;)
                DynamicDictionary errorModel = new DynamicDictionary();
                errorModel.Add(new KeyValuePair <string, dynamic>("ErrorMessage", errorMessage));

                // Hash up the Error model so DotLiquid will understand it
                hashedModel =
                    Hash.FromAnonymousObject(new
                {
                    Model = new DynamicDrop(errorModel)
                });

                // Grab the error HTML from the embedded resource and build up the DotLiquid template.
                String errorHtml = LoadResource(@"500.liquid");
                parsed = Template.Parse(errorHtml);
            }
            catch (Exception ex)
            {
                status = HttpStatusCode.InternalServerError;
                // Build the error message
                String errorMessage = String.Format("Error: {0}", ex.Message);

                // Create the error model with a Nancy DynamicDictionary because i can ;)
                DynamicDictionary errorModel = new DynamicDictionary();
                errorModel.Add(new KeyValuePair <string, dynamic>("ErrorMessage", errorMessage));

                // Hash up the Error model so DotLiquid will understand it
                hashedModel =
                    Hash.FromAnonymousObject(new
                {
                    Model = new DynamicDrop(errorModel)
                });

                // Grab the error HTML from the embedded resource
                String errorHtml = LoadResource(@"500.liquid");
                parsed = Template.Parse(errorHtml);
            }

            // Build the response
            return(new HtmlResponse(statusCode: status, contents: stream =>
            {
                parsed.Render(stream, new RenderParameters
                {
                    LocalVariables = hashedModel,
                    Registers = Hash.FromAnonymousObject(new { nancy = renderContext })
                });
            }));
        }
Example #60
0
 private static string GetViewFolderKey(ViewLocationResult viewLocationResult)
 {
     return(string.Concat(viewLocationResult.Location, Path.DirectorySeparatorChar, viewLocationResult.Name, ".", viewLocationResult.Extension));
 }