/// <inheritdoc />
        public async Task InvokeAsync(ViewComponentContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var methodInfo = context.ViewComponentDescriptor?.MethodInfo;
            if (methodInfo == null)
            {
                throw new InvalidOperationException(Resources.FormatPropertyOfTypeCannotBeNull(
                    nameof(ViewComponentDescriptor.MethodInfo),
                    nameof(ViewComponentDescriptor)));
            }

            var isAsync = typeof(Task).IsAssignableFrom(methodInfo.ReturnType);
            IViewComponentResult result;
            if (isAsync)
            {
                result = await InvokeAsyncCore(context);
            }
            else
            {
                // We support falling back to synchronous if there is no InvokeAsync method, in this case we'll still
                // execute the IViewResult asynchronously.
                result = InvokeSyncCore(context);
            }

            await result.ExecuteAsync(context);
        }
        private static ViewComponentContext GetViewComponentContext(IView view, Stream stream)
        {
            var actionContext = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
            var viewContext = new ViewContext(
                actionContext,
                view,
                viewData,
                new TempDataDictionary(actionContext.HttpContext, new SessionStateTempDataProvider()),
                TextWriter.Null,
                new HtmlHelperOptions());

            var writer = new StreamWriter(stream) { AutoFlush = true };

            var viewComponentDescriptor = new ViewComponentDescriptor()
            {
                TypeInfo = typeof(object).GetTypeInfo(),
            };

            var viewComponentContext = new ViewComponentContext(
                viewComponentDescriptor,
                new Dictionary<string, object>(),
                new HtmlTestEncoder(),
                viewContext,
                writer);

            return viewComponentContext;
        }
        /// <inheritdoc />
        public virtual object Create(ViewComponentContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var componentType = context.ViewComponentDescriptor.TypeInfo;

            if (componentType.IsValueType ||
                componentType.IsInterface ||
                componentType.IsAbstract ||
                (componentType.IsGenericType && componentType.IsGenericTypeDefinition))
            {
                var message = Resources.FormatValueInterfaceAbstractOrOpenGenericTypesCannotBeActivated(
                    componentType.FullName,
                    GetType().FullName);

                throw new InvalidOperationException(message);
            }

            var viewComponent = _typeActivatorCache.CreateInstance<object>(
                context.ViewContext.HttpContext.RequestServices,
                context.ViewComponentDescriptor.TypeInfo.AsType());

            return viewComponent;
        }
        /// <summary>
        /// Encodes and writes the <see cref="Content"/>.
        /// </summary>
        /// <param name="context">The <see cref="ViewComponentContext"/>.</param>
        public void Execute(ViewComponentContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            context.HtmlEncoder.Encode(context.Writer, Content);
        }
        private void PrepareViewComponentContext(HttpTestContext testContext, ViewComponentContext viewComponentContext)
        {
            this.TestContext = testContext;
            this.Arguments = viewComponentContext.Arguments;
            this.HtmlEncoder = viewComponentContext.HtmlEncoder;
            this.ViewComponentDescriptor = viewComponentContext.ViewComponentDescriptor;
            this.ViewContext = viewComponentContext.ViewContext;

            TestHelper.SetActionContextToAccessor(this.ViewContext);
        }
        public void Activate(ViewComponentContext viewComponentContext, object viewComponent)
        {
            var propertiesToActivate = propertyActivatorCache.GetOrAdd(viewComponent.GetType(), getPropertiesToActivate);

            for (var i = 0; i < propertiesToActivate.Length; i++)
            {
                var activateInfo = propertiesToActivate[i];
                activateInfo.Activate(viewComponent, viewComponentContext);
            }
        }
        public static ViewComponentContextMock FromViewComponentContext(HttpTestContext testContext, ViewComponentContext viewComponentContext)
        {
            CommonValidator.CheckForNullReference(testContext, nameof(HttpTestContext));
            CommonValidator.CheckForNullReference(viewComponentContext, nameof(ViewComponentContext));

            viewComponentContext.ViewComponentDescriptor = viewComponentContext.ViewComponentDescriptor ?? new ViewComponentDescriptor();
            viewComponentContext.ViewContext = ViewContextMock.FromViewContext(testContext, viewComponentContext.ViewContext ?? new ViewContext());
            viewComponentContext.Arguments = viewComponentContext.Arguments ?? new Dictionary<string, object>();
            viewComponentContext.HtmlEncoder = viewComponentContext.HtmlEncoder ?? HtmlEncoder.Default;

            return new ViewComponentContextMock(testContext, viewComponentContext);
        }
        public ObjectMethodExecutor GetViewComponentMethodExecutor(ViewComponentContext viewComponentContext)
        {
            var cache = CurrentCache;
            var viewComponentDescriptor = viewComponentContext.ViewComponentDescriptor;

            ObjectMethodExecutor executor;
            if (cache.Entries.TryGetValue(viewComponentDescriptor, out executor))
            {
                return executor;
            }

            executor = ObjectMethodExecutor.Create(viewComponentDescriptor.MethodInfo, viewComponentDescriptor.TypeInfo);

            cache.Entries.TryAdd(viewComponentDescriptor, executor);
            return executor;
        }
        /// <inheritdoc />
        public virtual void Release(ViewComponentContext context, object viewComponent)
        {
            if (context == null)
            {
                throw new InvalidOperationException(nameof(context));
            }

            if (viewComponent == null)
            {
                throw new InvalidOperationException(nameof(viewComponent));
            }

            var disposable = viewComponent as IDisposable;
            if (disposable != null)
            {
                disposable.Dispose();
            }
        }
        /// <inheritdoc />
        public virtual void Release(ViewComponentContext context, object viewComponent)
        {
            if (context == null)
            {
                throw new InvalidOperationException(nameof(context));
            }

            if (viewComponent == null)
            {
                throw new InvalidOperationException(nameof(viewComponent));
            }

            var disposable = viewComponent as IDisposable;

            if (disposable != null)
            {
                disposable.Dispose();
            }
        }
        public async Task InvokeAsync(ViewComponentContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var executor = _viewComponentInvokerCache.GetViewComponentMethodExecutor(context);

            var returnType = executor.MethodReturnType;

            if (returnType == typeof(void) || returnType == typeof(Task))
            {
                throw new InvalidOperationException(Resources.ViewComponent_MustReturnValue);
            }

            IViewComponentResult result;
            object?component = null;

            try
            {
                component = _viewComponentFactory.CreateViewComponent(context);
                if (executor.IsMethodAsync)
                {
                    result = await InvokeAsyncCore(executor, component, context);
                }
                else
                {
                    // We support falling back to synchronous if there is no InvokeAsync method, in this case we'll still
                    // execute the IViewResult asynchronously.
                    result = InvokeSyncCore(executor, component, context);
                }
            }
            finally
            {
                if (component != null)
                {
                    await _viewComponentFactory.ReleaseViewComponentAsync(context, executor);
                }
            }

            await result.ExecuteAsync(context);
        }
Exemple #12
0
        public void Constructor_PerformsDefensiveCopies()
        {
            // Arrange
            var httpContext   = new DefaultHttpContext();
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
            var viewData      = new ViewDataDictionary(new EmptyModelMetadataProvider());
            var tempData      = new TempDataDictionary(httpContext, new SessionStateTempDataProvider());
            var viewContext   = new ViewContext(
                actionContext,
                NullView.Instance,
                viewData,
                tempData,
                TextWriter.Null,
                new HtmlHelperOptions());

            var viewComponentDescriptor = new ViewComponentDescriptor();

            // Act
            var viewComponentContext = new ViewComponentContext(
                viewComponentDescriptor,
                new Dictionary <string, object>(),
                new HtmlTestEncoder(),
                viewContext,
                TextWriter.Null);

            // Assert
            // New ViewContext but initial View and TextWriter copied over.
            Assert.NotSame(viewContext, viewComponentContext.ViewContext);
            Assert.Same(tempData, viewComponentContext.TempData);
            Assert.Same(viewContext.View, viewComponentContext.ViewContext.View);
            Assert.Same(viewContext.Writer, viewComponentContext.ViewContext.Writer);

            // Double-check the convenience properties.
            Assert.Same(viewComponentContext.ViewContext.ViewData, viewComponentContext.ViewData);
            Assert.Same(viewComponentContext.ViewContext.TempData, viewComponentContext.TempData);
            Assert.Same(viewComponentContext.ViewContext.Writer, viewComponentContext.Writer);

            // New VDD instance but initial ModelMetadata copied over.
            Assert.NotSame(viewData, viewComponentContext.ViewData);
            Assert.Same(viewData.ModelMetadata, viewComponentContext.ViewData.ModelMetadata);
        }
        public void ReleaseViewComponent_CallsDispose_OnTheInstance()
        {
            // Arrange
            var context = new ViewComponentContext
            {
            };

            var component = new ActivablePropertiesViewComponent();

            var viewComponentActivator = new Mock<IViewComponentActivator>();
            viewComponentActivator.Setup(vca => vca.Release(context, component))
                .Callback<ViewComponentContext, object>((c, o) => (o as IDisposable)?.Dispose());

            var factory = new DefaultViewComponentFactory(viewComponentActivator.Object);

            // Act
            factory.ReleaseViewComponent(context, component);

            // Assert
            Assert.Equal(true, component.Disposed);
        }
        private async Task <IHtmlContent> InvokeCoreAsync(ViewComponentDescriptor descriptor, object arguments)
        {
            var argumentDictionary = GetArgumentDictionary(descriptor, arguments);

            var viewBuffer = new ViewBuffer(_viewBufferScope, descriptor.FullName, ViewBuffer.ViewComponentPageSize);

            using (var writer = new ViewBufferTextWriter(viewBuffer, _viewContext.Writer.Encoding))
            {
                var context = new ViewComponentContext(descriptor, argumentDictionary, _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(viewBuffer);
            }
        }
        public void ReleaseViewComponent_CallsDispose_OnTheInstance()
        {
            // Arrange
            var context = new ViewComponentContext
            {
            };

            var component = new ActivablePropertiesViewComponent();

            var viewComponentActivator = new Mock <IViewComponentActivator>();

            viewComponentActivator.Setup(vca => vca.Release(context, component))
            .Callback <ViewComponentContext, object>((c, o) => (o as IDisposable)?.Dispose());

            var factory = new DefaultViewComponentFactory(viewComponentActivator.Object);

            // Act
            factory.ReleaseViewComponent(context, component);

            // Assert
            Assert.True(component.Disposed);
        }
Exemple #16
0
        /// <inheritdoc />
        public object Create(ViewComponentContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var componentType = context.ViewComponentDescriptor.TypeInfo;

            if (componentType == null)
            {
                throw new ArgumentException(Resources.FormatPropertyOfTypeCannotBeNull(
                                                nameof(context.ViewComponentDescriptor.TypeInfo),
                                                nameof(context.ViewComponentDescriptor)));
            }

            var viewComponent = _typeActivatorCache.CreateInstance <object>(
                context.ViewContext.HttpContext.RequestServices,
                context.ViewComponentDescriptor.TypeInfo.AsType());

            return(viewComponent);
        }
        public void Constructor_PerformsDefensiveCopies()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
            var viewContext = new ViewContext(
                actionContext,
                NullView.Instance,
                viewData,
                new TempDataDictionary(httpContext, new SessionStateTempDataProvider()),
                TextWriter.Null,
                new HtmlHelperOptions());

            var viewComponentDescriptor = new ViewComponentDescriptor();

            // Act
            var viewComponentContext = new ViewComponentContext(
                viewComponentDescriptor,
                new Dictionary<string, object>(),
                new HtmlTestEncoder(),
                viewContext,
                TextWriter.Null);

            // Assert
            // New ViewContext but initial View and TextWriter copied over.
            Assert.NotSame(viewContext, viewComponentContext.ViewContext);
            Assert.Same(viewContext.View, viewComponentContext.ViewContext.View);
            Assert.Same(viewContext.Writer, viewComponentContext.ViewContext.Writer);

            // Double-check the convenience properties.
            Assert.Same(viewComponentContext.ViewContext.ViewData, viewComponentContext.ViewData);
            Assert.Same(viewComponentContext.ViewContext.Writer, viewComponentContext.Writer);

            // New VDD instance but initial ModelMetadata copied over.
            Assert.NotSame(viewData, viewComponentContext.ViewData);
            Assert.Same(viewData.ModelMetadata, viewComponentContext.ViewData.ModelMetadata);
        }
        public async Task ReleaseViewComponentAsync_CallsDisposeAsync_OnAsyncDisposableComponents()
        {
            // Arrange
            var context = new ViewComponentContext
            {
            };

            var component = new AsyncDisposableViewComponent();

            var viewComponentActivator = new Mock <IViewComponentActivator>();

            viewComponentActivator.Setup(vca => vca.ReleaseAsync(context, component))
            .Callback <ViewComponentContext, object>((c, o) => (o as IAsyncDisposable)?.DisposeAsync())
            .Returns(default(ValueTask));

            var factory = new DefaultViewComponentFactory(viewComponentActivator.Object);

            // Act
            await factory.ReleaseViewComponentAsync(context, component);

            // Assert
            Assert.True(component.Disposed);
        }
        public void CreateViewComponent_ActivatesProperties_OnTheInstance()
        {
            // Arrange
            var context = new ViewComponentContext
            {
            };

            var component = new ActivablePropertiesViewComponent();
            var activator = new Mock<IViewComponentActivator>();
            activator.Setup(a => a.Create(context))
                .Returns(component);

            var factory = new DefaultViewComponentFactory(activator.Object);

            // Act
            var result = factory.CreateViewComponent(context);

            // Assert
            var activablePropertiesComponent = Assert.IsType<ActivablePropertiesViewComponent>(result);

            Assert.Same(component, activablePropertiesComponent);
            Assert.Same(component.Context, activablePropertiesComponent.Context);
        }
        public void CreateViewComponent_ActivatesProperties_OnTheInstance()
        {
            // Arrange
            var context = new ViewComponentContext
            {
            };

            var component = new ActivablePropertiesViewComponent();
            var activator = new Mock <IViewComponentActivator>();

            activator.Setup(a => a.Create(context))
            .Returns(component);

            var factory = new DefaultViewComponentFactory(activator.Object);

            // Act
            var result = factory.CreateViewComponent(context);

            // Assert
            var activablePropertiesComponent = Assert.IsType <ActivablePropertiesViewComponent>(result);

            Assert.Same(component, activablePropertiesComponent);
            Assert.Same(component.Context, activablePropertiesComponent.Context);
        }
 private static IViewEngine ResolveViewEngine(ViewComponentContext context)
 {
     return(context.ViewContext.HttpContext.RequestServices.GetRequiredService <ICompositeViewEngine>());
 }
 /// <summary>Releases the view component.</summary>
 /// <param name="context">The <see cref="ViewComponentContext"/> associated with the viewComponent.</param>
 /// <param name="viewComponent">The view component to release.</param>
 public void Release(ViewComponentContext context, object viewComponent)
 {
     // No-op.
 }
Exemple #23
0
        private async Task <IViewComponentResult> InvokeAsyncCore(ObjectMethodExecutor executor, ViewComponentContext context)
        {
            var component = _viewComponentFactory.CreateViewComponent(context);

            using (_logger.ViewComponentScope(context))
            {
                var arguments = ControllerActionExecutor.PrepareArguments(context.Arguments, executor);

                _diagnosticSource.BeforeViewComponent(context, component);
                _logger.ViewComponentExecuting(context, arguments);

                var startTimestamp = _logger.IsEnabled(LogLevel.Debug) ? Stopwatch.GetTimestamp() : 0;

                object resultAsObject  = null;
                var    taskGenericType = executor.TaskGenericType;

                if (taskGenericType == typeof(IViewComponentResult))
                {
                    resultAsObject = await(Task <IViewComponentResult>) executor.Execute(component, arguments);
                }
                else if (taskGenericType == typeof(string))
                {
                    resultAsObject = await(Task <string>) executor.Execute(component, arguments);
                }
                else if (taskGenericType == typeof(IHtmlContent))
                {
                    resultAsObject = await(Task <IHtmlContent>) executor.Execute(component, arguments);
                }
                else
                {
                    resultAsObject = await executor.ExecuteAsync(component, arguments);
                }

                var viewComponentResult = CoerceToViewComponentResult(resultAsObject);
                _logger.ViewComponentExecuted(context, startTimestamp, viewComponentResult);
                _diagnosticSource.AfterViewComponent(context, viewComponentResult, component);

                _viewComponentFactory.ReleaseViewComponent(context, component);

                return(viewComponentResult);
            }
        }
Exemple #24
0
        private IViewComponentResult InvokeSyncCore(ObjectMethodExecutor executor, object component, ViewComponentContext context)
        {
            using (_logger.ViewComponentScope(context))
            {
                var arguments = PrepareArguments(context.Arguments, executor);

                _diagnosticListener.BeforeViewComponent(context, component);
                _logger.ViewComponentExecuting(context, arguments);

                var    stopwatch = ValueStopwatch.StartNew();
                object?result;

                result = executor.Execute(component, arguments);

                var viewComponentResult = CoerceToViewComponentResult(result);
                _logger.ViewComponentExecuted(context, stopwatch.GetElapsedTime(), viewComponentResult);
                _diagnosticListener.AfterViewComponent(context, viewComponentResult, component);

                return(viewComponentResult);
            }
        }
 /// <summary>Creates a view component.</summary>
 /// <param name="context"></param>
 /// <returns>A view component instance.</returns>
 public object Create(ViewComponentContext context) =>
     this.container.GetInstance(context.ViewComponentDescriptor.TypeInfo.AsType());
 /// <inheritdoc />
 public virtual void Release(ViewComponentContext context, object viewComponent)
 {
 }
Exemple #27
0
        private async Task <IViewComponentResult> InvokeAsyncCore(ObjectMethodExecutor executor, object component, ViewComponentContext context)
        {
            using (_logger.ViewComponentScope(context))
            {
                var arguments = PrepareArguments(context.Arguments, executor);

                _diagnosticListener.BeforeViewComponent(context, component);
                _logger.ViewComponentExecuting(context, arguments);

                var stopwatch = ValueStopwatch.StartNew();

                object resultAsObject;
                var    returnType = executor.MethodReturnType;

                if (returnType == typeof(Task <IViewComponentResult>))
                {
                    var task = executor.Execute(component, arguments);
                    if (task is null)
                    {
                        throw new InvalidOperationException(Resources.ViewComponent_MustReturnValue);
                    }

                    resultAsObject = await(Task <IViewComponentResult>) task;
                }
                else if (returnType == typeof(Task <string>))
                {
                    var task = executor.Execute(component, arguments);
                    if (task is null)
                    {
                        throw new InvalidOperationException(Resources.ViewComponent_MustReturnValue);
                    }

                    resultAsObject = await(Task <string>) task;
                }
                else if (returnType == typeof(Task <IHtmlContent>))
                {
                    var task = executor.Execute(component, arguments);
                    if (task is null)
                    {
                        throw new InvalidOperationException(Resources.ViewComponent_MustReturnValue);
                    }

                    resultAsObject = await(Task <IHtmlContent>) task;
                }
                else
                {
                    resultAsObject = await executor.ExecuteAsync(component, arguments);
                }

                var viewComponentResult = CoerceToViewComponentResult(resultAsObject);
                _logger.ViewComponentExecuted(context, stopwatch.GetElapsedTime(), viewComponentResult);
                _diagnosticListener.AfterViewComponent(context, viewComponentResult, component);

                return(viewComponentResult);
            }
        }
        /// <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);
            }
        }
        public void WithCustomViewComponentContextShouldSetItToAccessor()
        {
            MyApplication
                .StartsFrom<DefaultStartup>()
                .WithServices(services =>
                {
                    services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
                });

            var actionDescriptor = new ActionDescriptor { DisplayName = "Test" };
            var context = new ViewComponentContext { ViewContext = new ViewContext { ActionDescriptor = actionDescriptor } };

            MyViewComponent<AccessorComponent>
                .Instance()
                .WithViewComponentContext(context)
                .ShouldPassForThe<AccessorComponent>(viewComponent =>
                {
                    Assert.NotNull(viewComponent);
                    Assert.NotNull(viewComponent.ActionContext);
                    Assert.Equal("Test", viewComponent.ActionContext.ActionDescriptor.DisplayName);
                });

            MyApplication.StartsFrom<DefaultStartup>();
        }
Exemple #30
0
        private async Task <IViewComponentResult> InvokeAsyncCore(ObjectMethodExecutor executor, ViewComponentContext context)
        {
            var component = _viewComponentFactory.CreateViewComponent(context);

            using (_logger.ViewComponentScope(context))
            {
                var arguments = PrepareArguments(context.Arguments, executor);

                _diagnosticSource.BeforeViewComponent(context, component);
                _logger.ViewComponentExecuting(context, arguments);

                var stopwatch = ValueStopwatch.StartNew();

                object resultAsObject;
                var    returnType = executor.MethodReturnType;

                if (returnType == typeof(Task <IViewComponentResult>))
                {
                    resultAsObject = await(Task <IViewComponentResult>) executor.Execute(component, arguments);
                }
                else if (returnType == typeof(Task <string>))
                {
                    resultAsObject = await(Task <string>) executor.Execute(component, arguments);
                }
                else if (returnType == typeof(Task <IHtmlContent>))
                {
                    resultAsObject = await(Task <IHtmlContent>) executor.Execute(component, arguments);
                }
                else
                {
                    resultAsObject = await executor.ExecuteAsync(component, arguments);
                }

                var viewComponentResult = CoerceToViewComponentResult(resultAsObject);
                _logger.ViewComponentExecuted(context, stopwatch.GetElapsedTime(), viewComponentResult);
                _diagnosticSource.AfterViewComponent(context, viewComponentResult, component);

                _viewComponentFactory.ReleaseViewComponent(context, component);

                return(viewComponentResult);
            }
        }
        /// <summary>
        /// Encodes and writes the <see cref="Content"/>.
        /// </summary>
        /// <param name="context">The <see cref="ViewComponentContext"/>.</param>
        /// <returns>A completed <see cref="Task"/>.</returns>
        public Task ExecuteAsync(ViewComponentContext context)
        {
            Execute(context);

            return TaskCache.CompletedTask;
        }
 public void Execute(ViewComponentContext context)
 {
 }
        private static ViewComponentContext GetViewComponentContext(
            IView view,
            ViewDataDictionary viewData,
            object diagnosticListener = null)
        {
            var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
            if (diagnosticListener == null)
            {
                diagnosticListener = new TestDiagnosticListener();
            }

            diagnosticSource.SubscribeWithAdapter(diagnosticListener);

            var serviceProvider = new Mock<IServiceProvider>();
            serviceProvider.Setup(s => s.GetService(typeof(DiagnosticSource))).Returns(diagnosticSource);

            var httpContext = new DefaultHttpContext();
            httpContext.RequestServices = serviceProvider.Object;

            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
            var viewContext = new ViewContext(
                actionContext,
                view,
                viewData,
                new TempDataDictionary(httpContext, new SessionStateTempDataProvider()),
                TextWriter.Null,
                new HtmlHelperOptions());

            var viewComponentDescriptor = new ViewComponentDescriptor()
            {
                ShortName = "Invoke",
                TypeInfo = typeof(object).GetTypeInfo(),
                MethodInfo = typeof(object).GetTypeInfo().DeclaredMethods.First()
            };

            var viewComponentContext = new ViewComponentContext(
                viewComponentDescriptor,
                new Dictionary<string, object>(),
                new HtmlTestEncoder(),
                viewContext,
                TextWriter.Null);

            return viewComponentContext;
        }
        public void ViewDataModelSetter_DoesNotThrow_IfValueIncompatibleWithSourceDeclaredType(
            object model,
            Type expectedType)
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
            var viewData = new ViewDataDictionary<int>(new EmptyModelMetadataProvider());
            var viewContext = new ViewContext(
                actionContext,
                NullView.Instance,
                viewData,
                new TempDataDictionary(httpContext, new SessionStateTempDataProvider()),
                TextWriter.Null,
                new HtmlHelperOptions());

            var viewComponentDescriptor = new ViewComponentDescriptor();
            var viewComponentContext = new ViewComponentContext(
                viewComponentDescriptor,
                new Dictionary<string, object>(),
                new HtmlTestEncoder(),
                viewContext,
                TextWriter.Null);

            // Act (does not throw)
            // Non-ints can be assigned despite type restrictions in the source ViewDataDictionary.
            viewComponentContext.ViewData.Model = model;

            // Assert
            Assert.Equal(expectedType, viewComponentContext.ViewData.ModelMetadata.ModelType);
        }
 private ViewComponentContextMock(HttpTestContext testContext, ViewComponentContext viewComponentContext)
 {
     this.PrepareViewComponentContext(testContext, viewComponentContext);
 }
        private async Task<IViewComponentResult> InvokeAsyncCore(ViewComponentContext context)
        {
            var component = _viewComponentFactory.CreateViewComponent(context);

            using (_logger.ViewComponentScope(context))
            {
                var method = context.ViewComponentDescriptor.MethodInfo;
                var arguments = ControllerActionExecutor.PrepareArguments(context.Arguments, method.GetParameters());

                var methodExecutor = _viewComponentInvokerCache.GetViewComponentMethodExecutor(context);

                _diagnosticSource.BeforeViewComponent(context, component);
                _logger.ViewComponentExecuting(context, arguments);

                var startTimestamp = _logger.IsEnabled(LogLevel.Debug) ? Stopwatch.GetTimestamp() : 0;
                var result = await ControllerActionExecutor.ExecuteAsync(methodExecutor, component, arguments);

                var viewComponentResult = CoerceToViewComponentResult(result);
                _logger.ViewComponentExecuted(context, startTimestamp, viewComponentResult);
                _diagnosticSource.AfterViewComponent(context, viewComponentResult, component);

                _viewComponentFactory.ReleaseViewComponent(context, component);

                return viewComponentResult;
            }
        }
        public Task ExecuteAsync(ViewComponentContext context)
        {
            Execute(context);

            return(Task.CompletedTask);
        }
 public Task ExecuteAsync(ViewComponentContext context)
 {
     return Task.FromResult(0);
 }