internal async Task ExecuteAsync(ActionContext context, ViewResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

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

            ViewEngineResult viewEngineResult = FindView(context, result);

            viewEngineResult.EnsureSuccessful(originalLocations: null);

            IView view = viewEngineResult.View;

            using (view as IDisposable)
            {
                await ExecuteAsync(
                    context,
                    view,
                    result.ViewData,
                    result.TempData,
                    result.ContentType,
                    result.StatusCode);
            }
        }
        public async Task ExecuteAsync(WidgetViewContext context)
        {
            var viewEngine          = ViewEngine ?? ResolveViewEngine(context);
            var viewContext         = context.ViewContext;
            var viewLocationService = ResolveViewLocationService(context);

            if (string.IsNullOrEmpty(ViewName))
            {
                ViewName = DefaultViewName;
            }

            var locations = viewLocationService.Search(context.ComponentDescriptor);

            ViewEngineResult result = null;

            foreach (var viewFormat in locations)
            {
                string viewFullName = string.Format(
                    CultureInfo.InvariantCulture,
                    viewFormat,
                    context.ComponentDescriptor.RootName,
                    ViewName
                    );

                result = viewEngine.FindView(context.ViewContext, viewFullName + ".cshtml", false);

                if (!result.Success)
                {
                    result = viewEngine.GetView(null, viewFullName + ".cshtml", false);
                }

                if (result.Success)
                {
                    break;
                }
            }

            IEnumerable <string> searchedLocations = result.SearchedLocations;

            var view = result.EnsureSuccessful(searchedLocations).View;

            using (view as IDisposable)
            {
                var childViewContext = new ViewContext(
                    viewContext,
                    view,
                    ViewData ?? context.ViewData,
                    context.Writer);

                await view.RenderAsync(childViewContext);
            }
        }
Beispiel #3
0
        public override async Task ExecuteResultAsync(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IServiceProvider          services = context.HttpContext.RequestServices;
            LocalizedViewFindExecutor executor = services.GetRequiredService <LocalizedViewFindExecutor>();
            ViewEngineResult          result   = executor.FindView(context, this);

            result.EnsureSuccessful(originalLocations: null);
            IView view = result.View;

            using (view as IDisposable)
            {
                await executor.ExecuteAsync(context, view, this);
            }
        }
        /// <summary>
        /// Locates and renders a view specified by <see cref="ViewName"/>. If <see cref="ViewName"/> is <c>null</c>,
        /// then the view name searched for is<c>&quot;Default&quot;</c>.
        /// </summary>
        /// <param name="context">The <see cref="ViewComponentContext"/> for the current component execution.</param>
        /// <returns>A <see cref="Task"/> which will complete when view rendering is completed.</returns>
        public async Task ExecuteAsync(ViewComponentContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            string viewName = ViewName;

            if (string.IsNullOrEmpty(viewName))
            {
                viewName = context.ViewComponentDescriptor.ShortName;
            }

            var viewEngine  = ViewEngine ?? ResolveViewEngine(context);
            var viewContext = context.ViewContext;

            // If view name was passed in is already a path, the view engine will handle this.
            ViewEngineResult result = viewEngine.GetView(viewContext.ExecutingFilePath, viewName, false);

            if (result == null || !result.Success)
            {
                // This will produce a string like:
                //
                //  Views/Shared/Components/Cart.cshtml
                //

                result = viewEngine.FindView(viewContext, string.Format(CultureInfo.InvariantCulture, "Components/{0}", viewName), false);
            }

            var view = result.EnsureSuccessful(result.SearchedLocations).View;

            using (view as IDisposable)
            {
                var childViewContext = new ViewContext(
                    viewContext,
                    view,
                    ViewData ?? context.ViewData,
                    context.Writer);
                await view.RenderAsync(childViewContext);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Locates and renders a module view specified by <see cref="ViewName"/>. If <see cref="ViewName"/> is <c>null</c>,
        /// then the view name searched for is<c>&quot;Default&quot;</c>.
        /// </summary>
        /// <param name="context">The <see cref="ViewComponentContext"/> for the current component execution.</param>
        /// <returns>A <see cref="Task"/> which will complete when view rendering is completed.</returns>
        public async Task ExecuteAsync(ViewComponentContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

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

            IModuleViewEngine moduleViewEngine = ViewEngine ?? ResolveModuleViewEngine(context);
            ViewContext       viewContext      = context.ViewContext;

            bool isNullOrEmptyViewName             = string.IsNullOrEmpty(ViewName);
            IEnumerable <string> originalLocations = null;

            string viewName = isNullOrEmptyViewName ? SiteConfiguration.DefaultModuleViewName : ViewName;

            string qualifiedViewName = string.Format(
                CultureInfo.InvariantCulture,
                ModulePathFormat,
                ModuleDefinitionPath,
                viewName);

            ViewEngineResult result = moduleViewEngine.FindModuleView(viewContext, qualifiedViewName);
            IView            view   = result.EnsureSuccessful(originalLocations).View;

            using (view as IDisposable)
            {
                var childViewContext = new ViewContext(
                    viewContext,
                    view,
                    ViewData ?? context.ViewData,
                    context.Writer);

                await view.RenderAsync(childViewContext);
            }
        }
        public static async Task RenderAsync(this HttpResponse response, string viewName, object?model = null, CancellationToken cancellationToken = default)
        {
            IRazorViewEngine  razorViewEngine  = response.HttpContext.RequestServices.GetRequiredService <IRazorViewEngine>();
            ITempDataProvider tempDataProvider = response.HttpContext.RequestServices.GetRequiredService <ITempDataProvider>();

            ActionContext    actionContext    = new ActionContext(response.HttpContext, new RouteData(), new ActionDescriptor());
            ViewEngineResult viewEngineResult = razorViewEngine.FindView(actionContext, viewName, true);

            viewEngineResult.EnsureSuccessful(Array.Empty <string>());
            IView view = viewEngineResult.View;
            ViewDataDictionary viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), actionContext.ModelState)
            {
                Model = model
            };
            TempDataDictionary tempData = new TempDataDictionary(actionContext.HttpContext, tempDataProvider);

            using TextWriter textWriter = new StringWriter();
            ViewContext viewContext = new ViewContext(actionContext, view, viewDictionary, tempData, textWriter, new HtmlHelperOptions());
            await view.RenderAsync(viewContext).ConfigureAwait(false);

            await response.WriteAsync(textWriter.ToString() !, cancellationToken).ConfigureAwait(false);
        }
        public virtual void IterationSetup()
        {
            _requestScope = _serviceProvider.CreateScope();

            _viewEngineResult = _viewEngine.GetView(null, ViewPath, true);
            _viewEngineResult.EnsureSuccessful(null);

            _actionContext = new ActionContext(
                new DefaultHttpContext()
            {
                RequestServices = _requestScope.ServiceProvider
            },
                _routeData,
                _actionDescriptor);

            _tempData = _tempDataDictionaryFactory.GetTempData(_actionContext.HttpContext);

            _viewDataDictionary = new ViewDataDictionary(
                _requestScope.ServiceProvider.GetRequiredService <IModelMetadataProvider>(),
                _actionContext.ModelState);
            _viewDataDictionary.Model = Model;

            _executor = _requestScope.ServiceProvider.GetRequiredService <BenchmarkViewExecutor>();
        }
        /// <summary>
        /// Locates and renders a view specified by <see cref="ViewName"/>. If <see cref="ViewName"/> is <c>null</c>,
        /// then the view name searched for is<c>&quot;Default&quot;</c>.
        /// </summary>
        /// <param name="context">The <see cref="ViewComponentContext"/> for the current component execution.</param>
        /// <returns>A <see cref="Task"/> which will complete when view rendering is completed.</returns>
        public async Task ExecuteAsync(ViewComponentContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var viewEngine            = ViewEngine ?? ResolveViewEngine(context);
            var viewContext           = context.ViewContext;
            var isNullOrEmptyViewName = string.IsNullOrEmpty(ViewName);

            ViewEngineResult     result            = null;
            IEnumerable <string> originalLocations = null;

            if (!isNullOrEmptyViewName)
            {
                // If view name was passed in is already a path, the view engine will handle this.
                result            = viewEngine.GetView(viewContext.ExecutingFilePath, ViewName, isMainPage: false);
                originalLocations = result.SearchedLocations;
            }

            if (result == null || !result.Success)
            {
                // This will produce a string like:
                //
                //  Components/Cart/Default
                //
                // The view engine will combine this with other path info to search paths like:
                //
                //  Views/Shared/Components/Cart/Default.cshtml
                //  Views/Home/Components/Cart/Default.cshtml
                //  Areas/Blog/Views/Shared/Components/Cart/Default.cshtml
                //
                // This supports a controller or area providing an override for component views.
                var viewName          = isNullOrEmptyViewName ? DefaultViewName : ViewName;
                var qualifiedViewName = string.Format(
                    CultureInfo.InvariantCulture,
                    ViewPathFormat,
                    context.ViewComponentDescriptor.ShortName,
                    viewName);

                result = viewEngine.FindView(viewContext, qualifiedViewName, isMainPage: false);
            }

            var view = result.EnsureSuccessful(originalLocations).View;

            using (view as IDisposable)
            {
                if (_diagnosticListener == null)
                {
                    _diagnosticListener = viewContext.HttpContext.RequestServices.GetRequiredService <DiagnosticListener>();
                }

                _diagnosticListener.ViewComponentBeforeViewExecute(context, view);

                var childViewContext = new ViewContext(
                    viewContext,
                    view,
                    ViewData ?? context.ViewData,
                    context.Writer);
                await view.RenderAsync(childViewContext);

                _diagnosticListener.ViewComponentAfterViewExecute(context, view);
            }
        }
Beispiel #9
0
        public async Task ExecuteAsync(ViewComponentContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var viewEngine            = ViewEngine ?? ResolveViewEngine(context);
            var viewContext           = context.ViewContext;
            var isNullOrEmptyViewName = string.IsNullOrEmpty(ViewName) || ViewName == DefaultViewName;

            ViewEngineResult     result            = null;
            IEnumerable <string> originalLocations = null;

            if (!isNullOrEmptyViewName)
            {
                // If view name was passed in is already a path, the view engine will handle this.
                result            = viewEngine.GetView(viewContext.ExecutingFilePath, ViewName, isMainPage: false);
                originalLocations = result.SearchedLocations;
            }

            if (result == null || !result.Success)
            {
                // IMPORTANT: This strips away the default naming convention that forces all View Components
                // to be placed in ~/Components/ComponentName/View.cshtml and instead allows for
                // significantly more customization as well as sub-components nested inside other
                // components' folders
                var qualifiedViewName = isNullOrEmptyViewName ? string.Format(
                    CultureInfo.InvariantCulture,
                    ViewPathFormat,
                    context.ViewComponentDescriptor.ShortName,
                    DefaultViewName)
                                        : ViewName;
                result = viewEngine.FindView(viewContext, qualifiedViewName, isMainPage: false);
            }

            var view = result.EnsureSuccessful(originalLocations).View;

            using (view as IDisposable)
            {
                var childViewContext = new ViewContext(
                    viewContext,
                    view,
                    ViewData ?? context.ViewData,
                    context.Writer);
                // IMPORTANT: This Try-Catch Encapsulates our modules ensuring an error in one module does not
                //   incur a 500 on the page and instead simply doesn't render anything
                try
                {
                    await view.RenderAsync(childViewContext);
                }
                catch (Exception e)
                {
                    var logger = ResolveLogger(context);
                    if (logger != null)
                    {
                        logger.LogError($"Failed to render module '{context.ViewComponentDescriptor.ShortName}'", e);
                        logger.LogDebug(e.Message);
                    }
                }
            }
        }