public async Task Write_WritesCharValues_ToUnderlyingStream_WhenNotBuffering()
        {
            // Arrange
            var unbufferedWriter = new Mock<TextWriter> { CallBase = true };
            unbufferedWriter.SetupGet(w => w.Encoding).Returns(Encoding.UTF8);
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");
            var writer = new RazorTextWriter(unbufferedWriter.Object, buffer, new HtmlTestEncoder());
            var buffer1 = new[] { 'a', 'b', 'c', 'd' };
            var buffer2 = new[] { 'd', 'e', 'f' };

            // Act
            writer.Flush();
            writer.Write('x');
            writer.Write(buffer1, 1, 2);
            writer.Write(buffer2);
            await writer.WriteAsync(buffer2, 1, 1);
            await writer.WriteLineAsync(buffer1);

            // Assert
            Assert.Null(buffer.BufferSegments);
            unbufferedWriter.Verify(v => v.Write('x'), Times.Once());
            unbufferedWriter.Verify(v => v.Write(buffer1, 1, 2), Times.Once());
            unbufferedWriter.Verify(v => v.Write(buffer1, 0, 4), Times.Once());
            unbufferedWriter.Verify(v => v.Write(buffer2, 0, 3), Times.Once());
            unbufferedWriter.Verify(v => v.WriteAsync(buffer2, 1, 1), Times.Once());
            unbufferedWriter.Verify(v => v.WriteLine(), Times.Once());
        }
        public void Write_WritesDataTypes_ToUnderlyingStream_WhenNotBuffering()
        {
            // Arrange
            var expected = new[] { "True", "3", "18446744073709551615", "Hello world", "3.14", "2.718" };
            var unbufferedWriter = new Mock<TextWriter>();
            unbufferedWriter.SetupGet(w => w.Encoding).Returns(Encoding.UTF8);
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");
            var writer = new RazorTextWriter(unbufferedWriter.Object, buffer, new HtmlTestEncoder());
            var testClass = new TestClass();

            // Act
            writer.Flush();
            writer.Write(true);
            writer.Write(3);
            writer.Write(ulong.MaxValue);
            writer.Write(testClass);
            writer.Write(3.14);
            writer.Write(2.718m);

            // Assert
            Assert.Null(buffer.BufferSegments);
            foreach (var item in expected)
            {
                unbufferedWriter.Verify(v => v.Write(item), Times.Once());
            }
        }
示例#3
0
        public void Append_CreatesNewSegments_WhenCurrentSegmentIsFull()
        {
            // Arrange
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");
            var expected = Enumerable.Range(0, TestViewBufferScope.DefaultBufferSize).Select(i => i.ToString());

            // Act
            foreach (var item in expected)
            {
                buffer.Append(item);
            }
            buffer.Append("Hello");
            buffer.Append("world");

            // Assert
            Assert.Equal(2, buffer.CurrentCount);
            Assert.Collection(buffer.BufferSegments,
                segment => Assert.Equal(expected, segment.Select(v => v.Value)),
                segment =>
                {
                    var array = segment;
                    Assert.Equal("Hello", array[0].Value);
                    Assert.Equal("world", array[1].Value);
                });
        }
示例#4
0
        /// <summary>
        /// Creates a new instance of <see cref="RazorTextWriter"/>.
        /// </summary>
        /// <param name="unbufferedWriter">The <see cref="TextWriter"/> to write output to when this instance
        /// is no longer buffering.</param>
        /// <param name="buffer">The <see cref="ViewBuffer"/> to buffer output to.</param>
        /// <param name="encoder">The HTML encoder.</param>
        public RazorTextWriter(TextWriter unbufferedWriter, ViewBuffer buffer, HtmlEncoder encoder)
        {
            UnbufferedWriter = unbufferedWriter;
            Buffer = buffer;
            HtmlEncoder = encoder;

            BufferedWriter = new HtmlContentWrapperTextWriter(buffer, unbufferedWriter.Encoding);
            TargetWriter = BufferedWriter;
        }
示例#5
0
        public void Append_AddsStringRazorValue()
        {
            // Arrange
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");

            // Act
            buffer.Append("Hello world");

            // Assert
            var segment = Assert.Single(buffer.BufferSegments);
            Assert.Equal(1, buffer.CurrentCount);
            Assert.Equal("Hello world", segment[0].Value);
        }
示例#6
0
        public void Append_AddsHtmlContentRazorValue()
        {
            // Arrange
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");
            var content = new HtmlString("hello-world");

            // Act
            buffer.AppendHtml(content);

            // Assert
            var segment = Assert.Single(buffer.BufferSegments);
            Assert.Equal(1, buffer.CurrentCount);
            Assert.Same(content, segment[0].Value);
        }
示例#7
0
        public void AppendHtml_AddsHtmlStringValues()
        {
            // Arrange
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");
            var value = "Hello world";

            // Act
            buffer.AppendHtml(value);

            // Assert
            var segment = Assert.Single(buffer.BufferSegments);
            Assert.Equal(1, buffer.CurrentCount);
            var htmlString = Assert.IsType<HtmlString>(segment[0].Value);
            Assert.Equal("Hello world", htmlString.ToString());
        }
        public void Write_WritesDataTypes_ToBuffer()
        {
            // Arrange
            var expected = new object[] { "True", "3", "18446744073709551615", "Hello world", "3.14", "2.718", "m" };
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");
            var writer = new RazorTextWriter(TextWriter.Null, buffer, new HtmlTestEncoder());

            // Act
            writer.Write(true);
            writer.Write(3);
            writer.Write(ulong.MaxValue);
            writer.Write(new TestClass());
            writer.Write(3.14);
            writer.Write(2.718m);
            writer.Write('m');

            // Assert
            Assert.Equal(expected, GetValues(buffer));
        }
        private async Task<IHtmlContent> InvokeCoreAsync(
            ViewComponentDescriptor descriptor,
            object arguments)
        {
            var viewBuffer = new ViewBuffer(_viewBufferScope, descriptor.FullName);
            using (var writer = new HtmlContentWrapperTextWriter(viewBuffer, _viewContext.Writer.Encoding))
            {
                var context = new ViewComponentContext(
                    descriptor,
                    PropertyHelper.ObjectToDictionary(arguments),
                    _htmlEncoder,
                    _viewContext,
                    writer);

                var invoker = _invokerFactory.CreateInstance(context);
                if (invoker == null)
                {
                    throw new InvalidOperationException(
                        Resources.FormatViewComponent_IViewComponentFactory_ReturnedNull(descriptor.FullName));
                }

                await invoker.InvokeAsync(context);
                return writer.ContentBuilder;
            }
        }
示例#10
0
 private static object[] GetValues(ViewBuffer buffer)
 {
     return buffer.BufferSegments
         .SelectMany(c => c)
         .Select(d => d.Value)
         .TakeWhile(d => d != null)
         .ToArray();
 }
示例#11
0
        public async Task WriteToAsync_WritesRazorValues_ToTextWriter()
        {
            // Arrange
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");
            var writer = new StringWriter();

            // Act
            buffer.Append("Hello");
            buffer.AppendHtml(new HtmlString(" world"));
            buffer.AppendHtml(" 123");

            await buffer.WriteToAsync(writer, new HtmlTestEncoder());

            // Assert
            Assert.Equal("Hello world 123", writer.ToString());
        }
示例#12
0
        public async Task WriteToAsync_WritesRazorValuesFromAllBuffers(int valuesToWrite)
        {
            // Arrange
            var buffer = new ViewBuffer(new TestViewBufferScope(4), "some-name");
            var writer = new StringWriter();
            var expected = string.Join("", Enumerable.Range(0, valuesToWrite).Select(_ => "abc"));

            // Act
            for (var i = 0; i < valuesToWrite; i++)
            {
                buffer.AppendHtml("abc");
            }

            await buffer.WriteToAsync(writer, new HtmlTestEncoder());

            // Assert
            Assert.Equal(expected, writer.ToString());
        }
示例#13
0
        public async Task WriteToAsync_WritesSelf_WhenWriterIsHtmlTextWriter()
        {
            // Arrange
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");
            var htmlWriter = new Mock<HtmlTextWriter>();
            htmlWriter.Setup(w => w.Write(buffer)).Verifiable();

            // Act
            buffer.Append("Hello world");
            await buffer.WriteToAsync(htmlWriter.Object, new HtmlTestEncoder());

            // Assert
            htmlWriter.Verify();
        }
示例#14
0
        public async Task Write_WritesStringValues_ToUnbufferedStream_WhenNotBuffering()
        {
            // Arrange
            var unbufferedWriter = new Mock<TextWriter>();
            unbufferedWriter.SetupGet(w => w.Encoding).Returns(Encoding.UTF8);
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");
            var writer = new RazorTextWriter(unbufferedWriter.Object, buffer, new HtmlTestEncoder());

            // Act
            await writer.FlushAsync();
            writer.Write("a");
            writer.WriteLine("ab");
            await writer.WriteAsync("ef");
            await writer.WriteLineAsync("gh");

            // Assert
            Assert.Null(buffer.BufferSegments);
            unbufferedWriter.Verify(v => v.Write("a"), Times.Once());
            unbufferedWriter.Verify(v => v.WriteLine("ab"), Times.Once());
            unbufferedWriter.Verify(v => v.WriteAsync("ef"), Times.Once());
            unbufferedWriter.Verify(v => v.WriteLineAsync("gh"), Times.Once());
        }
示例#15
0
        public void WriteLine_WritesDataTypes_ToBuffer()
        {
            // Arrange
            var newLine = Environment.NewLine;
            var expected = new List<object> { "False", newLine, "1.1", newLine, "3", newLine };
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");
            var writer = new RazorTextWriter(TextWriter.Null, buffer, new HtmlTestEncoder());

            // Act
            writer.WriteLine(false);
            writer.WriteLine(1.1f);
            writer.WriteLine(3L);

            // Assert
            Assert.Equal(expected, GetValues(buffer));
        }
示例#16
0
        private async Task<RazorTextWriter> RenderPageAsync(
            IRazorPage page,
            ViewContext context,
            bool invokeViewStarts)
        {
            Debug.Assert(_bufferScope != null);
            var buffer = new ViewBuffer(_bufferScope, page.Path);
            var razorTextWriter = new RazorTextWriter(context.Writer, buffer, _htmlEncoder);

            // The writer for the body is passed through the ViewContext, allowing things like HtmlHelpers
            // and ViewComponents to reference it.
            var oldWriter = context.Writer;
            var oldFilePath = context.ExecutingFilePath;
            context.Writer = razorTextWriter;
            context.ExecutingFilePath = page.Path;

            try
            {
                if (invokeViewStarts)
                {
                    // Execute view starts using the same context + writer as the page to render.
                    await RenderViewStartsAsync(context);
                }

                await RenderPageCoreAsync(page, context);
                return razorTextWriter;
            }
            finally
            {
                context.Writer = oldWriter;
                context.ExecutingFilePath = oldFilePath;
                razorTextWriter.Dispose();
            }
        }
示例#17
0
        public void WriteLine_WritesDataTypes_ToUnbufferedStream_WhenNotBuffering()
        {
            // Arrange
            var unbufferedWriter = new Mock<TextWriter>();
            unbufferedWriter.SetupGet(w => w.Encoding).Returns(Encoding.UTF8);
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");
            var writer = new RazorTextWriter(unbufferedWriter.Object, buffer, new HtmlTestEncoder());

            // Act
            writer.Flush();
            writer.WriteLine(false);
            writer.WriteLine(1.1f);
            writer.WriteLine(3L);

            // Assert
            Assert.Null(buffer.BufferSegments);
            unbufferedWriter.Verify(v => v.Write("False"), Times.Once());
            unbufferedWriter.Verify(v => v.Write("1.1"), Times.Once());
            unbufferedWriter.Verify(v => v.Write("3"), Times.Once());
            unbufferedWriter.Verify(v => v.WriteLine(), Times.Exactly(3));
        }
示例#18
0
        public async Task Write_WithHtmlString_WritesValueWithoutEncoding()
        {
            // Arrange
            var buffer = new ViewBuffer(new TestViewBufferScope(), string.Empty);
            var writer = new RazorTextWriter(TextWriter.Null, buffer, new HtmlTestEncoder());

            var page = CreatePage(p =>
            {
                p.Write(new HtmlString("Hello world"));
            });
            page.ViewContext.Writer = writer;

            // Act
            await page.ExecuteAsync();

            // Assert
            Assert.Equal("Hello world", HtmlContentUtilities.HtmlContentToString(writer.Buffer));
        }
示例#19
0
        public async Task WriteLines_WritesCharBuffer()
        {
            // Arrange
            var newLine = Environment.NewLine;
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");
            var writer = new RazorTextWriter(TextWriter.Null, buffer, new HtmlTestEncoder());

            // Act
            writer.WriteLine();
            await writer.WriteLineAsync();

            // Assert
            var actual = GetValues(buffer);
            Assert.Equal<object>(new[] { newLine, newLine }, actual);
        }
示例#20
0
        public void Write_HtmlContent_AfterFlush_GoesToStream()
        {
            // Arrange
            var stringWriter = new StringWriter();
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");
            var writer = new RazorTextWriter(stringWriter, buffer, new HtmlTestEncoder());
            writer.Flush();

            var content = new HtmlString("Hello, world!");

            // Act
            writer.Write(content);

            // Assert
            Assert.Equal("Hello, world!", stringWriter.ToString());
        }
示例#21
0
        public async Task Write_WritesStringBuffer()
        {
            // Arrange
            var newLine = Environment.NewLine;
            var input1 = "Hello";
            var input2 = "from";
            var input3 = "ASP";
            var input4 = ".Net";
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");
            var writer = new RazorTextWriter(TextWriter.Null, buffer, new HtmlTestEncoder());

            // Act
            writer.Write(input1);
            writer.WriteLine(input2);
            await writer.WriteAsync(input3);
            await writer.WriteLineAsync(input4);

            // Assert
            var actual = GetValues(buffer);
            Assert.Equal<object>(new[] { input1, input2, newLine, input3, input4, newLine }, actual);
        }
示例#22
0
        public void Clear_ResetsBackingBufferAndIndex(int valuesToWrite)
        {
            // Arrange
            var buffer = new ViewBuffer(new TestViewBufferScope(), "some-name");

            // Act
            for (var i = 0; i < valuesToWrite; i++)
            {
                buffer.Append("Hello");
            }
            buffer.Clear();
            buffer.Append("world");

            // Assert
            var segment = Assert.Single(buffer.BufferSegments);
            Assert.Equal(1, buffer.CurrentCount);
            Assert.Equal("world", segment[0].Value);
        }
示例#23
0
        public IHtmlContent Render()
        {
            var defaultActions = GetDefaultActions();
            var modeViewPath = _readOnly ? DisplayTemplateViewPath : EditorTemplateViewPath;

            foreach (string viewName in GetViewNames())
            {
                var viewEngineResult = _viewEngine.GetView(_viewContext.ExecutingFilePath, viewName, isMainPage: false);
                if (!viewEngineResult.Success)
                {
                    var fullViewName = modeViewPath + "/" + viewName;
                    viewEngineResult = _viewEngine.FindView(_viewContext, fullViewName, isMainPage: false);
                }

                if (viewEngineResult.Success)
                {
                    var viewBuffer = new ViewBuffer(_bufferScope, viewName);
                    using (var writer = new HtmlContentWrapperTextWriter(viewBuffer, _viewContext.Writer.Encoding))
                    {
                        // Forcing synchronous behavior so users don't have to await templates.
                        var view = viewEngineResult.View;
                        using (view as IDisposable)
                        {
                            var viewContext = new ViewContext(_viewContext, viewEngineResult.View, _viewData, writer);
                            var renderTask = viewEngineResult.View.RenderAsync(viewContext);
                            renderTask.GetAwaiter().GetResult();
                            return writer.ContentBuilder;
                        }
                    }
                }

                Func<IHtmlHelper, IHtmlContent> defaultAction;
                if (defaultActions.TryGetValue(viewName, out defaultAction))
                {
                    return defaultAction(MakeHtmlHelper(_viewContext, _viewData));
                }
            }

            throw new InvalidOperationException(
                Resources.FormatTemplateHelpers_NoTemplate(_viewData.ModelExplorer.ModelType.FullName));
        }