예제 #1
0
파일: RazorView.cs 프로젝트: Nakro/Mvc
        private async Task<RazorTextWriter> RenderPageAsync(IRazorPage page,
                                                            ViewContext context,
                                                            bool executeViewStart)
        {
            using (var bufferedWriter = new RazorTextWriter(context.Writer.Encoding))
            {
                // The writer for the body is passed through the ViewContext, allowing things like HtmlHelpers
                // and ViewComponents to reference it.
                var oldWriter = context.Writer;
                context.Writer = bufferedWriter;
                try
                {
                    if (executeViewStart)
                    {
                        // Execute view starts using the same context + writer as the page to render.
                        await RenderViewStartAsync(context);
                    }

                    await RenderPageCoreAsync(page, context);
                    return bufferedWriter;
                }
                finally
                {
                    context.Writer = oldWriter;
                }
            }
        }
예제 #2
0
        private async Task<StringCollectionTextWriter> RenderPageAsync(IRazorPage page,
                                                                ViewContext context,
                                                                bool executeViewStart)
        {
            var bufferedWriter = new StringCollectionTextWriter(context.Writer.Encoding);
            var writer = (TextWriter)bufferedWriter;
            
            // 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 = writer;
            context.ExecutingFilePath = page.Path;

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

                await RenderPageCoreAsync(page, context);
                return bufferedWriter;
            }
            finally
            {
                context.Writer = oldWriter;
                context.ExecutingFilePath = oldFilePath;
                writer.Dispose();
            }
        }
예제 #3
0
        public Task Execute(IRazorPage page, IDictionary<string, object> environment, ITrace tracer)
        {
            Requires.NotNull(page, "page");
            Requires.NotNull(environment, "environment");
            Requires.NotNull(tracer, "tracer");

            return ExecuteCore(page, environment, tracer);
        }
예제 #4
0
 /// <summary>
 /// Initializes a new instance of <see cref="RazorView"/>
 /// </summary>
 /// <param name="viewEngine">The <see cref="IRazorViewEngine"/> used to locate Layout pages.</param>
 /// <param name="pageActivator">The <see cref="IRazorPageActivator"/> used to activate pages.</param>
 /// <param name="viewStartProvider">The <see cref="IViewStartProvider"/> used for discovery of _ViewStart
 /// <param name="razorPage">The <see cref="IRazorPage"/> instance to execute.</param>
 /// <param name="isPartial">Determines if the view is to be executed as a partial.</param>
 /// pages</param>
 public RazorView(IRazorViewEngine viewEngine,
                  IViewStartProvider viewStartProvider,
                  IRazorPage razorPage,
                  bool isPartial)
 {
     _viewEngine = viewEngine;
     _viewStartProvider = viewStartProvider;
     RazorPage = razorPage;
     IsPartial = isPartial;
 }
예제 #5
0
파일: RazorView.cs 프로젝트: Nakro/Mvc
 /// <summary>
 /// Initializes a new instance of RazorView
 /// </summary>
 /// <param name="page">The page to execute</param>
 /// <param name="pageFactory">The view factory used to instantiate additional views.</param>
 /// <param name="pageActivator">The <see cref="IRazorPageActivator"/> used to activate pages.</param>
 /// <param name="executeViewHierarchy">A value that indiciates whether the view hierarchy that involves 
 /// view start and layout pages are executed as part of the executing the page.</param>
 public RazorView([NotNull] IRazorPageFactory pageFactory,
                  [NotNull] IRazorPageActivator pageActivator,
                  [NotNull] IViewStartProvider viewStartProvider,
                  [NotNull] IRazorPage page,
                  bool executeViewHierarchy)
 {
     _pageFactory = pageFactory;
     _pageActivator = pageActivator;
     _viewStartProvider = viewStartProvider;
     _page = page;
     _executeViewHierarchy = executeViewHierarchy;
 }
예제 #6
0
파일: RazorView.cs 프로젝트: zyonet/Mvc
        private async Task <IBufferedTextWriter> RenderPageAsync(
            IRazorPage page,
            ViewContext context,
            bool executeViewStart)
        {
            var razorTextWriter = new RazorTextWriter(context.Writer, context.Writer.Encoding, _htmlEncoder);
            var writer          = (TextWriter)razorTextWriter;
            var bufferedWriter  = (IBufferedTextWriter)razorTextWriter;

            if (EnableInstrumentation)
            {
                writer         = _pageExecutionFeature.DecorateWriter(razorTextWriter);
                bufferedWriter = writer as IBufferedTextWriter;
                if (bufferedWriter == null)
                {
                    var message = Resources.FormatInstrumentation_WriterMustBeBufferedTextWriter(
                        nameof(TextWriter),
                        _pageExecutionFeature.GetType().FullName,
                        typeof(IBufferedTextWriter).FullName);
                    throw new InvalidOperationException(message);
                }
            }

            // 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            = writer;
            context.ExecutingFilePath = page.Path;

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

                await RenderPageCoreAsync(page, context);

                return(bufferedWriter);
            }
            finally
            {
                context.Writer            = oldWriter;
                context.ExecutingFilePath = oldFilePath;
                writer.Dispose();
            }
        }
예제 #7
0
        private async Task <ViewBufferTextWriter> RenderPageAsync(
            IRazorPage page,
            ViewContext context,
            bool invokeViewStarts)
        {
            var writer = context.Writer as ViewBufferTextWriter;

            if (writer == null)
            {
                Debug.Assert(_bufferScope != null);

                // If we get here, this is likely the top-level page (not a partial) - this means
                // that context.Writer is wrapping the output stream. We need to buffer, so create a buffered writer.
                var buffer = new ViewBuffer(_bufferScope, page.Path, ViewBuffer.ViewPageSize);
                writer = new ViewBufferTextWriter(buffer, context.Writer.Encoding, _htmlEncoder, context.Writer);
            }
            else
            {
                // This means we're writing something like a partial, where the output needs to be buffered.
                // Create a new buffer, but without the ability to flush.
                var buffer = new ViewBuffer(_bufferScope, page.Path, ViewBuffer.ViewPageSize);
                writer = new ViewBufferTextWriter(buffer, context.Writer.Encoding);
            }

            // 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            = writer;
            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(writer);
            }
            finally
            {
                context.Writer            = oldWriter;
                context.ExecutingFilePath = oldFilePath;
            }
        }
예제 #8
0
        private ViewEngineResult CreateFoundResult(ActionContext actionContext,
                                                   IRazorPage page,
                                                   string viewName,
                                                   bool partial)
        {
            // A single request could result in creating multiple IRazorView instances (for partials, view components)
            // and might store state. We'll use the service container to create new instances as we require.

            var services = actionContext.HttpContext.RequestServices;
            var view     = services.GetRequiredService <IRazorView>();

            view.Contextualize(page, partial);
            return(ViewEngineResult.Found(viewName, view));
        }
예제 #9
0
        /// <summary>
        /// Initializes a new instance of <see cref="RazorPageResult"/> for a successful discovery.
        /// </summary>
        /// <param name="name">The name of the page that was located.</param>
        /// <param name="page">The located <see cref="IRazorPage"/>.</param>
        public RazorPageResult(string name, IRazorPage page)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (page == null)
            {
                throw new ArgumentNullException(nameof(page));
            }

            Name = name;
            Page = page;
        }
예제 #10
0
        /// <summary>
        /// Add CSS next to this page. Client will call at the RequestPath
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public static HtmlString AddAssociatedCssTag(IRazorPage page)
        {
            if (page == null)
            {
                return(null);
            }
            var version = GetVersion(page, ".css");

            if (version.HasNoContent())
            {
                return(null);
            }

            return(new HtmlString("<link rel='stylesheet' href='{0}.css{1}'>".FilledWith(page.Path.Replace("/Pages", RequestPath), version)));
        }
예제 #11
0
        public async Task RenderPageAsync(RenderRequest request)
        {
            using (IServiceScope scope = _serviceScopeFactory.CreateScope())
            {
                IServiceProvider serviceProvider = scope.ServiceProvider;
                IRazorPage       page            = GetPageFromStream(serviceProvider, request);
                IView            view            = GetViewFromStream(serviceProvider, request, page);

                using (StreamWriter writer = request.Output.GetWriter())
                {
                    Microsoft.AspNetCore.Mvc.Rendering.ViewContext viewContext = GetViewContext(serviceProvider, request, view, writer);
                    await viewContext.View.RenderAsync(viewContext);
                }
            }
        }
예제 #12
0
        /// <summary>
        /// Add JS next to this page. Client will call at the RequestPath
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public static HtmlString AddAssociatedJsTag(IRazorPage page)
        {
            if (page == null)
            {
                return(null);
            }
            var version = GetVersion(page, ".js");

            if (version.HasNoContent())
            {
                return(null);
            }

            return(new HtmlString("<script src='{0}.js{1}'></script>".FilledWith(page.Path.Replace("/Pages", RequestPath), version)));
        }
예제 #13
0
파일: RazorView.cs 프로젝트: zyonet/Mvc
 /// <summary>
 /// Initializes a new instance of <see cref="RazorView"/>
 /// </summary>
 /// <param name="viewEngine">The <see cref="IRazorViewEngine"/> used to locate Layout pages.</param>
 /// <param name="pageActivator">The <see cref="IRazorPageActivator"/> used to activate pages.</param>
 /// <param name="viewStartProvider">The <see cref="IViewStartProvider"/> used for discovery of _ViewStart
 /// <param name="razorPage">The <see cref="IRazorPage"/> instance to execute.</param>
 /// <param name="htmlEncoder">The HTML encoder.</param>
 /// <param name="isPartial">Determines if the view is to be executed as a partial.</param>
 /// pages</param>
 public RazorView(
     IRazorViewEngine viewEngine,
     IRazorPageActivator pageActivator,
     IViewStartProvider viewStartProvider,
     IRazorPage razorPage,
     IHtmlEncoder htmlEncoder,
     bool isPartial)
 {
     _viewEngine        = viewEngine;
     _pageActivator     = pageActivator;
     _viewStartProvider = viewStartProvider;
     RazorPage          = razorPage;
     _htmlEncoder       = htmlEncoder;
     IsPartial          = isPartial;
 }
예제 #14
0
        /// <summary>
        /// Initializes a new instance of <see cref="RazorPageResult"/> for a successful discovery.
        /// </summary>
        /// <param name="name">The name of the page that was located.</param>
        /// <param name="page">The located <see cref="IRazorPage"/>.</param>
        public RazorPageResult(string name, IRazorPage page)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (page == null)
            {
                throw new ArgumentNullException(nameof(page));
            }

            Name = name;
            Page = page;
        }
예제 #15
0
 /// <summary>
 /// Initializes a new instance of <see cref="RazorView"/>
 /// </summary>
 /// <param name="viewEngine">The <see cref="IRazorViewEngine"/> used to locate Layout pages.</param>
 /// <param name="pageActivator">The <see cref="IRazorPageActivator"/> used to activate pages.</param>
 /// <param name="viewStartProvider">The <see cref="IViewStartProvider"/> used for discovery of _ViewStart
 /// <param name="razorPage">The <see cref="IRazorPage"/> instance to execute.</param>
 /// <param name="htmlEncoder">The HTML encoder.</param>
 /// <param name="isPartial">Determines if the view is to be executed as a partial.</param>
 /// pages</param>
 public RazorView(
     IRazorViewEngine viewEngine,
     IRazorPageActivator pageActivator,
     IViewStartProvider viewStartProvider,
     IRazorPage razorPage,
     IHtmlEncoder htmlEncoder,
     bool isPartial)
 {
     _viewEngine = viewEngine;
     _pageActivator = pageActivator;
     _viewStartProvider = viewStartProvider;
     RazorPage = razorPage;
     _htmlEncoder = htmlEncoder;
     IsPartial = isPartial;
 }
예제 #16
0
    public static T GetValueForTenant(this IRazorPage page, string setting, T defaultValue = default(T))
    {
        var service       = page.ViewContext.HttpContext.RequestServices.GetService();
        var tenant        = service.GetCurrentTenant();
        var configuration = page.ViewContext.HttpContext.RequestServices.GetService();
        var section       = configuration.GetSection("Tenants").GetSection(tenant);

        if (section.Exists())
        {
            return(section.GetValue(setting, defaultValue));
        }
        else
        {
            return(configuration.GetValue(setting, defaultValue));
        }
    }
예제 #17
0
        public static T GetValueForTenant <T>(this IRazorPage page, string setting, T defaultValue = default(T))
        {
            var service       = page.ViewContext.HttpContext.RequestServices.GetService <ITenantService>();
            var tenant        = service.GetCurrentTenant();
            var configuration = page.ViewContext.HttpContext.RequestServices.GetService <IConfiguration>();
            var section       = configuration.GetSection(nameof(ConfigurationExtensions.Tenants)).GetSection(tenant);

            if (section.Exists())
            {
                return(section.GetValue <T>(setting, defaultValue));
            }
            else
            {
                return(configuration.GetValue <T>(setting, defaultValue));
            }
        }
예제 #18
0
        private async Task RenderPageCoreAsync(IRazorPage page, ViewContext context)
        {
            page.ViewContext = context;
            _pageActivator.Activate(page, context);

            _diagnosticSource.BeforeViewPage(page, context);

            try
            {
                await page.ExecuteAsync();
            }
            finally
            {
                _diagnosticSource.AfterViewPage(page, context);
            }
        }
예제 #19
0
        /// <inheritdoc />
        public void Activate(IRazorPage page, ViewContext context)
        {
            if (page == null)
            {
                throw new ArgumentNullException(nameof(page));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var propertyActivator = GetOrAddCacheEntry(page);

            propertyActivator.Activate(page, context);
        }
        public IRazorPage CreateInstance([NotNull] string relativePath, Stream stream)
        {
            if (relativePath.StartsWith("~/", StringComparison.Ordinal))
            {
                // For tilde slash paths, drop the leading ~ to make it work with the underlying IFileProvider.
                relativePath = relativePath.Substring(1);
            }

            // Code below is taken from CompilerCache (specifically OnCacheMiss) which is responsible for managing the compilation step in MVC

            // Check the file
            var fileProvider = stream == null ? (IFileProvider)_fileProvider : new WyamStreamFileProvider(_fileProvider, stream);
            var fileInfo     = fileProvider.GetFileInfo(relativePath);

            if (!fileInfo.Exists)
            {
                return(null);
            }

            // If relative path is the root, it probably means this isn't from reading a file so don't bother with caching
            IExecutionCache cache    = relativePath == "/" ? null : _executionContext.ExecutionCache;
            string          key      = null;
            Type            pageType = null;

            if (cache != null)
            {
                key = relativePath + " " + RazorFileHash.GetHash(fileInfo);
                if (!cache.TryGetValue(key, out pageType))
                {
                    pageType = null;
                }
            }

            // Compile and store in cache if not found
            if (pageType == null)
            {
                var relativeFileInfo = new RelativeFileInfo(fileInfo, relativePath);
                pageType = _razorcompilationService.Compile(relativeFileInfo);
                cache?.Set(key, pageType);
            }

            // Create an return a new page instance
            IRazorPage page = (IRazorPage)Activator.CreateInstance(pageType);

            page.Path = relativePath;
            return(page);
        }
예제 #21
0
파일: RazorView.cs 프로젝트: RehanSaeed/Mvc
        private async Task<IBufferedTextWriter> RenderPageAsync(IRazorPage page,
                                                                ViewContext context,
                                                                bool executeViewStart)
        {
            var razorTextWriter = new RazorTextWriter(context.Writer, context.Writer.Encoding);
            var writer = (TextWriter)razorTextWriter;
            var bufferedWriter = (IBufferedTextWriter)razorTextWriter;

            if (EnableInstrumentation)
            {
                writer = _pageExecutionFeature.DecorateWriter(razorTextWriter);
                bufferedWriter = writer as IBufferedTextWriter;
                if (bufferedWriter == null)
                {
                    var message = Resources.FormatInstrumentation_WriterMustBeBufferedTextWriter(
                        nameof(TextWriter),
                        _pageExecutionFeature.GetType().FullName,
                        typeof(IBufferedTextWriter).FullName);
                    throw new InvalidOperationException(message);
                }
            }

            // 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 = writer;
            context.ExecutingFilePath = page.Path;

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

                await RenderPageCoreAsync(page, context);
                return bufferedWriter;
            }
            finally
            {
                context.Writer = oldWriter;
                context.ExecutingFilePath = oldFilePath;
                writer.Dispose();
            }
        }
예제 #22
0
        public TchRazorView(
            IReadOnlyList <IRazorPage> viewStartPages,
            IRazorPage razorPage)
        {
            if (viewStartPages == null)
            {
                throw new ArgumentNullException(nameof(viewStartPages));
            }

            if (razorPage == null)
            {
                throw new ArgumentNullException(nameof(razorPage));
            }

            ViewStartPages = viewStartPages;
            RazorPage      = razorPage;
        }
예제 #23
0
 private static void AfterViewPageImpl(
     this DiagnosticListener diagnosticListener,
     IRazorPage page,
     ViewContext viewContext)
 {
     if (diagnosticListener.IsEnabled(Diagnostics.AfterViewPageEventData.EventName))
     {
         diagnosticListener.Write(
             Diagnostics.AfterViewPageEventData.EventName,
             new AfterViewPageEventData(
                 page,
                 viewContext,
                 viewContext.ActionDescriptor,
                 viewContext.HttpContext
                 ));
     }
 }
예제 #24
0
        public static string AddFileVersionToPath(this IRazorPage page, string path)
        {
            try
            {
                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsettings.json");

                var configuration = builder.Build();
                var version       = configuration["FileVersions"];
                var versionPath   = $"{path}?v={version}";
                return(versionPath);
            }
            catch (Exception ex) {
                return(path);
            }
        }
예제 #25
0
        /// <summary>
        /// Initializes a new instance of <see cref="RazorView"/>
        /// </summary>
        /// <param name="viewEngine">The <see cref="IRazorViewEngine"/> used to locate Layout pages.</param>
        /// <param name="pageActivator">The <see cref="IRazorPageActivator"/> used to activate pages.</param>
        /// <param name="viewStartPages">The sequence of <see cref="IRazorPage" /> instances executed as _ViewStarts.
        /// </param>
        /// <param name="razorPage">The <see cref="IRazorPage"/> instance to execute.</param>
        /// <param name="htmlEncoder">The HTML encoder.</param>
        /// <param name="diagnosticSource">The <see cref="DiagnosticSource"/>.</param>
        public RazorView(
            IRazorViewEngine viewEngine,
            IRazorPageActivator pageActivator,
            IReadOnlyList <IRazorPage> viewStartPages,
            IRazorPage razorPage,
            HtmlEncoder htmlEncoder,
            DiagnosticSource diagnosticSource)
        {
            if (viewEngine == null)
            {
                throw new ArgumentNullException(nameof(viewEngine));
            }

            if (pageActivator == null)
            {
                throw new ArgumentNullException(nameof(pageActivator));
            }

            if (viewStartPages == null)
            {
                throw new ArgumentNullException(nameof(viewStartPages));
            }

            if (razorPage == null)
            {
                throw new ArgumentNullException(nameof(razorPage));
            }

            if (htmlEncoder == null)
            {
                throw new ArgumentNullException(nameof(htmlEncoder));
            }

            if (diagnosticSource == null)
            {
                throw new ArgumentNullException(nameof(diagnosticSource));
            }

            _viewEngine       = viewEngine;
            _pageActivator    = pageActivator;
            ViewStartPages    = viewStartPages;
            RazorPage         = razorPage;
            _htmlEncoder      = htmlEncoder;
            _diagnosticSource = diagnosticSource;
        }
예제 #26
0
 private static void AfterViewPageImpl(
     this DiagnosticListener diagnosticListener,
     IRazorPage page,
     ViewContext viewContext)
 {
     if (diagnosticListener.IsEnabled("Microsoft.AspNetCore.Mvc.Razor.AfterViewPage"))
     {
         diagnosticListener.Write(
             "Microsoft.AspNetCore.Mvc.Razor.AfterViewPage",
             new
         {
             page             = page,
             viewContext      = viewContext,
             actionDescriptor = viewContext.ActionDescriptor,
             httpContext      = viewContext.HttpContext,
         });
     }
 }
예제 #27
0
 public static void AfterViewPage(
     this DiagnosticSource diagnosticSource,
     IRazorPage page,
     ViewContext viewContext)
 {
     if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.Razor.AfterViewPage"))
     {
         diagnosticSource.Write(
             "Microsoft.AspNetCore.Mvc.Razor.AfterViewPage",
             new
         {
             page             = page,
             viewContext      = viewContext,
             actionDescriptor = viewContext.ActionDescriptor,
             httpContext      = viewContext.HttpContext,
         });
     }
 }
예제 #28
0
        private ViewEngineResult CreateViewEngineResult(ViewLocationCacheResult result, string viewName)
        {
            if (!result.Success)
            {
                return ViewEngineResult.NotFound(viewName, result.SearchedLocations);
            }

            var page = result.ViewEntry.PageFactory();

            var viewStarts = new IRazorPage[result.ViewStartEntries.Count];
            for (var i = 0; i < viewStarts.Length; i++)
            {
                var viewStartItem = result.ViewStartEntries[i];
                viewStarts[i] = viewStartItem.PageFactory();
            }

            var view = new RazorView(this, _pageActivator, viewStarts, page, _htmlEncoder);
            return ViewEngineResult.Found(viewName, view);
        }
예제 #29
0
        /// <summary>用户只有拥有当前菜单的指定权限</summary>
        /// <param name="page">页面</param>
        /// <param name="flags">是否拥有多个权限中的任意一个,或的关系。如果需要表示与的关系,可以传入一个多权限位合并</param>
        /// <returns></returns>
        public static Boolean Has(this IRazorPage page, params PermissionFlags[] flags)
        {
            // 没有用户时无权
            var user = page.ViewContext.ViewBag.User as IUser ?? page.ViewContext.HttpContext.User.Identity as IUser;

            if (user == null)
            {
                return(false);
            }

            // 没有菜单时不做权限控制
            var menu = page.ViewContext.ViewBag.Menu as IMenu;

            if (menu == null)
            {
                return(true);
            }

            return(user.Has(menu, flags));
        }
예제 #30
0
        private async Task <TextWriter> RenderPageAsync(
            IRazorPage page,
            ViewContext context,
            bool invokeViewStarts)
        {
            var writer = context.Writer as StringWriter;

            if (writer == null)
            {
                writer = new StringWriter();
            }
            // 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            = writer;
            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(writer);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                context.Writer            = oldWriter;
                context.ExecutingFilePath = oldFilePath;
            }
        }
예제 #31
0
        /// <summary>
        /// Gets the view for an input document (which is different than the view for a layout, partial, or
        /// other indirect view because it's not necessarily on disk or in the file system).
        /// </summary>
        private IView GetViewFromStream(string relativePath, Stream stream, string viewStartLocation, string layoutLocation,
                                        IRazorViewEngine viewEngine, IRazorPageActivator pageActivator, HtmlEncoder htmlEncoder,
                                        IRazorPageFactoryProvider pageFactoryProvider, IFileProvider rootFileProvider, IRazorCompilationService razorCompilationService)
        {
            IEnumerable <string> viewStartLocations = viewStartLocation != null
                ? new [] { viewStartLocation }
                : ViewHierarchyUtility.GetViewStartLocations(relativePath);
            List <IRazorPage> viewStartPages = viewStartLocations
                                               .Select(pageFactoryProvider.CreateFactory)
                                               .Where(x => x.Success)
                                               .Select(x => x.RazorPageFactory())
                                               .Reverse()
                                               .ToList();
            IRazorPage page = GetPageFromStream(relativePath, stream, rootFileProvider, razorCompilationService);

            if (layoutLocation != null)
            {
                page.Layout = layoutLocation;
            }
            return(new RazorView(viewEngine, pageActivator, viewStartPages, page, htmlEncoder));
        }
예제 #32
0
        internal virtual ViewEngineResult CreateViewEngineResult(PublicViewLocationCacheResult result, string viewName)
        {
            if (!result.Success)
            {
                return(ViewEngineResult.NotFound(viewName, result.SearchedLocations));
            }

            var page = result.ViewEntry.PageFactory();
            var cnt  = result.ViewStartEntries.Count;

            var viewStarts = new IRazorPage[result.ViewStartEntries.Count];

            for (var i = 0; i < cnt; i++)
            {
                var viewStartItem = result.ViewStartEntries[i];
                viewStarts[i] = viewStartItem.PageFactory();
            }

            var view = new RazorView(this, pageActivator, viewStarts, page, htmlEncoder, diagnosticListener);

            return(ViewEngineResult.Found(viewName, view));
        }
예제 #33
0
        internal RazorPagePropertyActivator GetOrAddCacheEntry(IRazorPage page)
        {
            var  pageType          = page.GetType();
            Type?providedModelType = null;

            if (page is IModelTypeProvider modelTypeProvider)
            {
                providedModelType = modelTypeProvider.GetModelType();
            }

            // We only need to vary by providedModelType since it varies at runtime. Defined model type
            // is synonymous with the pageType and consequently does not need to be accounted for in the cache key.
            var cacheKey = new CacheKey(pageType, providedModelType);

            if (!_activationInfo.TryGetValue(cacheKey, out var propertyActivator))
            {
                // Look for a property named "Model". If it is non-null, we'll assume this is
                // the equivalent of TModel Model property on RazorPage<TModel>.
                //
                // Otherwise if we don't have a model property the activator will just skip setting
                // the view data.
                var modelType = providedModelType;
                if (modelType == null)
                {
                    modelType = pageType.GetRuntimeProperty(ModelPropertyName)?.PropertyType;
                }

                propertyActivator = new RazorPagePropertyActivator(
                    pageType,
                    modelType,
                    _metadataProvider,
                    _propertyAccessors);

                propertyActivator = _activationInfo.GetOrAdd(cacheKey, propertyActivator);
            }

            return(propertyActivator);
        }
예제 #34
0
        /// <summary>
        /// Initializes a new instance of <see cref="RazorView"/>
        /// </summary>
        /// <param name="viewEngine">The <see cref="IRazorViewEngine"/> used to locate Layout pages.</param>
        /// <param name="pageActivator">The <see cref="IRazorPageActivator"/> used to activate pages.</param>
        /// <param name="viewStartPages">The sequence of <see cref="IRazorPage" /> instances executed as _ViewStarts.
        /// </param>
        /// <param name="razorPage">The <see cref="IRazorPage"/> instance to execute.</param>
        /// <param name="htmlEncoder">The HTML encoder.</param>
        public RazorView(
            IRazorViewEngine viewEngine,
            IRazorPageActivator pageActivator,
            IReadOnlyList<IRazorPage> viewStartPages,
            IRazorPage razorPage,
            HtmlEncoder htmlEncoder)
        {
            if (viewEngine == null)
            {
                throw new ArgumentNullException(nameof(viewEngine));
            }

            if (pageActivator == null)
            {
                throw new ArgumentNullException(nameof(pageActivator));
            }

            if (viewStartPages == null)
            {
                throw new ArgumentNullException(nameof(viewStartPages));
            }

            if (razorPage == null)
            {
                throw new ArgumentNullException(nameof(razorPage));
            }

            if (htmlEncoder == null)
            {
                throw new ArgumentNullException(nameof(htmlEncoder));
            }

            _viewEngine = viewEngine;
            _pageActivator = pageActivator;
            ViewStartPages = viewStartPages;
            RazorPage = razorPage;
            _htmlEncoder = htmlEncoder;
        }
 public Task ShowAsync(string width, string height, string title, string body,
                       Func <Task> messageCallbackDelegate = null, int timeElapsing = 0, IRazorPage razorPage = null)
 {
     TimeElapsing         = timeElapsing;
     RazorPage            = razorPage;
     MessageDelegate      = messageCallbackDelegate;
     TaskCompletionSource = new TaskCompletionSource();
     Height    = height;
     Width     = width;
     Title     = title;
     Body      = body;
     IsVisible = true;
     if (TimeElapsing > 0 && RazorPage != null)
     {
         WaitTask = Task.Run(async() =>
         {
             int timeCounter = 0;
             while (true)
             {
                 if (timeCounter > TimeElapsing)
                 {
                     if (messageCallbackDelegate != null)
                     {
                         await messageCallbackDelegate();
                     }
                     await RazorPage.NeedInvokeAsync(() =>
                     {
                         RazorPage.NeedRefresh();
                     });
                     break;
                 }
                 await Task.Delay(500);
                 timeCounter += 500;
             }
         });
     }
     return(TaskCompletionSource.Task);
 }
예제 #36
0
        /// <summary>
        /// Executes a Razor Page asynchronously.
        /// </summary>
        public virtual Task ExecuteAsync(PageContext pageContext, PageResult result)
        {
            if (pageContext == null)
            {
                throw new ArgumentNullException(nameof(pageContext));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            if (result.Model != null)
            {
                pageContext.ViewData.Model = result.Model;
            }

            OnExecuting(pageContext);

            var viewStarts = new IRazorPage[pageContext.ViewStartFactories.Count];

            for (var i = 0; i < pageContext.ViewStartFactories.Count; i++)
            {
                viewStarts[i] = pageContext.ViewStartFactories[i]();
            }

            var viewContext = result.Page.ViewContext;

            viewContext.View = new RazorView(
                _razorViewEngine,
                _razorPageActivator,
                viewStarts,
                new RazorPageAdapter(result.Page),
                _htmlEncoder,
                _diagnosticSource);

            return(ExecuteAsync(viewContext, result.ContentType, result.StatusCode));
        }
예제 #37
0
        /// <inheritdoc />
        public void Activate(IRazorPage page, ViewContext context)
        {
            if (page == null)
            {
                throw new ArgumentNullException(nameof(page));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var activationInfo = _activationInfo.GetOrAdd(page.GetType(),
                                                          CreateViewActivationInfo);

            context.ViewData = CreateViewDataDictionary(context, activationInfo);

            for (var i = 0; i < activationInfo.PropertyActivators.Length; i++)
            {
                var activateInfo = activationInfo.PropertyActivators[i];
                activateInfo.Activate(page, context);
            }
        }
예제 #38
0
        void ISetLayout.Set(IRazorPage page, PageInfo pageInfo, ViewContext viewContext)
        {
            viewContext.ViewBag.PageInfo = pageInfo;

            var request     = viewContext.HttpContext.Request;
            var isPjaxModal = request.IsPjaxModal();

            if (isPjaxModal)
            {
                page.Layout = this.RelativeViewPath("Modal.cshtml");
                return;
            }

            var isPjax    = request.IsPjax();
            var menuModel = new MenuModel();

            menuModel.Layout = isPjax
                ? this.RelativeViewPath("MasterPjax.cshtml")
                : this.RelativeViewPath("Master.cshtml");

            viewContext.ViewBag.MenuModel = menuModel;
            page.Layout = this.RelativeViewPath("Menu.cshtml");
        }
예제 #39
0
        public static void SetAppLayout(
            this IRazorPage page,
            string title,
            string baseUrl,
            bool enableBlazorServerSide = false,
            bool enableBlazorClientSide = false,
            string clientStyles         = null,
            string customScript         = null)
        {
            page.Layout = "_appLayout";

            var model = new AppLayoutModel
            {
                Title   = title,
                BaseUrl = baseUrl,
                EnableBlazorServerSide = enableBlazorServerSide,
                EnableBlazorClientSide = enableBlazorClientSide,
                ClientStyles           = clientStyles,
                CustomScript           = customScript,
            };

            page.ViewContext.ViewData["appLayoutModel"] = model;
        }
예제 #40
0
        /// <inheritdoc />
        public void Activate(IRazorPage page, ViewContext context)
        {
            if (page == null)
            {
                throw new ArgumentNullException(nameof(page));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var activationInfo = _activationInfo.GetOrAdd(page.GetType(),
                                                          CreateViewActivationInfo);

            context.ViewData = CreateViewDataDictionary(context, activationInfo);

            for (var i = 0; i < activationInfo.PropertyActivators.Length; i++)
            {
                var activateInfo = activationInfo.PropertyActivators[i];
                activateInfo.Activate(page, context);
            }
        }
예제 #41
0
        /// <inheritdoc />
        public IView GetView(
            IRazorViewEngine viewEngine,
            IRazorPage page,
            bool isPartial)
        {
            if (viewEngine == null)
            {
                throw new ArgumentNullException(nameof(viewEngine));
            }

            if (page == null)
            {
                throw new ArgumentNullException(nameof(page));
            }

            var razorView = new RazorView(
                viewEngine,
                _pageActivator,
                _viewStartProvider,
                page,
                _htmlEncoder,
                isPartial);
            return razorView;
        }
예제 #42
0
 private ViewEngineResult CreateFoundResult(IRazorPage page, string viewName, bool partial)
 {
     var view = new RazorView(_pageFactory,
                              _pageActivator,
                              _viewStartProvider,
                              page,
                              executeViewHierarchy: !partial);
     return ViewEngineResult.Found(viewName, view);
 }
예제 #43
0
 private ActivationResult(bool success, IRazorPage page)
 {
     Success = success;
     Page = page;
 }
예제 #44
0
 public static ActivationResult Successful(IRazorPage page)
 {
     return new ActivationResult(true, page);
 }
예제 #45
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();
            }
        }
예제 #46
0
        private async Task RenderPageCoreAsync(IRazorPage page, ViewContext context)
        {
            page.IsPartial = IsPartial;
            page.ViewContext = context;

            await page.ExecuteAsync();
        }
예제 #47
0
 private static async Task ExecuteCore(IRazorPage page, IDictionary<string, object> environment, ITrace tracer)
 {
     await page.Run(new RazorRequest(environment), new RazorResponse(environment));
 }
예제 #48
0
        private async Task<ViewBufferTextWriter> RenderPageAsync(
            IRazorPage page,
            ViewContext context,
            bool invokeViewStarts)
        {
            var writer = context.Writer as ViewBufferTextWriter;
            if (writer == null)
            {
                Debug.Assert(_bufferScope != null);

                // If we get here, this is likely the top-level page (not a partial) - this means
                // that context.Writer is wrapping the output stream. We need to buffer, so create a buffered writer.
                var buffer = new ViewBuffer(_bufferScope, page.Path, ViewBuffer.ViewPageSize);
                writer = new ViewBufferTextWriter(buffer, context.Writer.Encoding, _htmlEncoder, context.Writer);
            }
            else
            {
                // This means we're writing something like a partial, where the output needs to be buffered.
                // Create a new buffer, but without the ability to flush.
                var buffer = new ViewBuffer(_bufferScope, page.Path, ViewBuffer.ViewPageSize);
                writer = new ViewBufferTextWriter(buffer, context.Writer.Encoding);
            }

            // 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 = writer;
            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 writer;
            }
            finally
            {
                context.Writer = oldWriter;
                context.ExecutingFilePath = oldFilePath;
            }
        }
예제 #49
0
 private Task RenderPageCoreAsync(IRazorPage page, ViewContext context)
 {
     page.ViewContext = context;
     _pageActivator.Activate(page, context);
     return page.ExecuteAsync();
 }
예제 #50
0
        private ViewEngineResult CreateViewEngineResult(ViewLocationCacheResult result, string viewName)
        {
            if (!result.Success)
            {
                return ViewEngineResult.NotFound(viewName, result.SearchedLocations);
            }

            var page = result.ViewEntry.PageFactory();

            var viewStarts = new IRazorPage[result.ViewStartEntries.Count];
            for (var i = 0; i < viewStarts.Length; i++)
            {
                var viewStartItem = result.ViewStartEntries[i];
                viewStarts[i] = viewStartItem.PageFactory();
            }

            var view = new RazorView(this, _pageActivator, viewStarts, page, _htmlEncoder);
            return ViewEngineResult.Found(viewName, view);
        }
예제 #51
0
        private Task RenderPageCoreAsync(IRazorPage page, ViewContext context)
        {
            page.IsPartial = IsPartial;
            page.ViewContext = context;
            if (EnableInstrumentation)
            {
                page.PageExecutionContext = _pageExecutionFeature.GetContext(page.Path, context.Writer);
            }

            _pageActivator.Activate(page, context);
            return page.ExecuteAsync();
        }