public void FindView_WritesDiagnostic_ViewFound()
        {
            // Arrange
            var diagnosticSource = new DiagnosticListener("Test");
            var listener = new TestDiagnosticListener();
            diagnosticSource.SubscribeWithAdapter(listener);

            var context = GetActionContext();
            var executor = GetViewExecutor(diagnosticSource);

            var viewName = "myview";
            var viewResult = new PartialViewResult
            {
                ViewName = viewName,
                ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
                TempData = Mock.Of<ITempDataDictionary>(),
            };

            // Act
            var viewEngineResult = executor.FindView(context, viewResult);

            // Assert
            Assert.Equal(viewName, viewEngineResult.ViewName);

            Assert.NotNull(listener.ViewFound);
            Assert.NotNull(listener.ViewFound.ActionContext);
            Assert.NotNull(listener.ViewFound.Result);
            Assert.NotNull(listener.ViewFound.View);
            Assert.True(listener.ViewFound.IsPartial);
            Assert.Equal("myview", listener.ViewFound.ViewName);
        }
        public OperationNameTelemetryInitializer(IHttpContextAccessor httpContextAccessor, DiagnosticListener telemetryListener) 
            : base(httpContextAccessor)
        {
            if (telemetryListener == null)
            {
                throw new ArgumentNullException("telemetryListener");
            }

            if (telemetryListener != null)
            {
                telemetryListener.SubscribeWithAdapter(this);
            }
        }
        public void FindView_WritesDiagnostic_ViewNotFound()
        {
            // Arrange
            var diagnosticSource = new DiagnosticListener("Test");
            var listener         = new TestDiagnosticListener();

            diagnosticSource.SubscribeWithAdapter(listener);

            var context  = GetActionContext();
            var executor = GetViewExecutor(diagnosticSource);

            var viewName   = "myview";
            var viewEngine = new Mock <IViewEngine>(MockBehavior.Strict);

            viewEngine
            .Setup(e => e.GetView(/*executingFilePath*/ null, "myview", /*isMainPage*/ false))
            .Returns(ViewEngineResult.NotFound("myview", Enumerable.Empty <string>()))
            .Verifiable();
            viewEngine
            .Setup(e => e.FindView(context, "myview", /*isMainPage*/ false))
            .Returns(ViewEngineResult.NotFound("myview", new string[] { "location/myview" }));

            var viewResult = new PartialViewResult
            {
                ViewName   = viewName,
                ViewEngine = viewEngine.Object,
                ViewData   = new ViewDataDictionary(new EmptyModelMetadataProvider()),
                TempData   = Mock.Of <ITempDataDictionary>(),
            };

            // Act
            var viewEngineResult = executor.FindView(context, viewResult);

            // Assert
            Assert.False(viewEngineResult.Success);

            Assert.NotNull(listener.ViewNotFound);
            Assert.NotNull(listener.ViewNotFound.ActionContext);
            Assert.NotNull(listener.ViewNotFound.Result);
            Assert.Equal(new string[] { "location/myview" }, listener.ViewNotFound.SearchedLocations);
            Assert.Equal("myview", listener.ViewNotFound.ViewName);
        }
Exemple #4
0
        public void InitializeSetsTelemetryOperationNameToControllerFromActionContext()
        {
            var actionContext = new ActionContext();

            actionContext.RouteData = new RouteData();
            actionContext.RouteData.Values.Add("controller", "home");

            var contextAccessor = HttpContextAccessorHelper.CreateHttpContextAccessor(new RequestTelemetry(), actionContext);

            var telemetryListener = new DiagnosticListener(TestListenerName);
            var initializer       = new MvcDiagnosticsListener();

            telemetryListener.SubscribeWithAdapter(initializer);
            telemetryListener.Write("Microsoft.AspNetCore.Mvc.BeforeAction",
                                    new { httpContext = contextAccessor.HttpContext, routeData = actionContext.RouteData });

            var telemetry = contextAccessor.HttpContext.Features.Get <RequestTelemetry>();

            Assert.Equal("GET home", telemetry.Name);
        }
        private static ViewComponentContext GetViewComponentContext(IView view, ViewDataDictionary viewData, object diagnosticListener = null)
        {
            var diagnosticSource = new DiagnosticListener("Microsoft.AspNet");

            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(new HttpContextAccessor(), new SessionStateTempDataProvider()),
                TextWriter.Null,
                new HtmlHelperOptions());

            var viewComponentDescriptor = new ViewComponentDescriptor()
            {
                Type = typeof(object),
            };

            var viewComponentContext = new ViewComponentContext(
                viewComponentDescriptor,
                new object[0],
                viewContext,
                TextWriter.Null);

            return(viewComponentContext);
        }
Exemple #6
0
        public void InitializeDoesNotIncludeRouteGroupKeyInParametersList()
        {
            var actionContext = new ActionContext();

            actionContext.RouteData = new RouteData();
            actionContext.RouteData.Values.Add("controller", "account");
            actionContext.RouteData.Values.Add("action", "login");
            actionContext.RouteData.Values.Add(TreeRouter.RouteGroupKey, "RouteGroupKey");

            var contextAccessor   = HttpContextAccessorHelper.CreateHttpContextAccessor(new RequestTelemetry(), actionContext);
            var telemetryListener = new DiagnosticListener(TestListenerName);
            var initializer       = new MvcDiagnosticsListener();

            telemetryListener.SubscribeWithAdapter(initializer);
            telemetryListener.Write("Microsoft.AspNetCore.Mvc.BeforeAction",
                                    new { httpContext = contextAccessor.HttpContext, routeData = actionContext.RouteData });

            var telemetry = contextAccessor.HttpContext.Features.Get <RequestTelemetry>();

            Assert.Equal("GET account/login", telemetry.Name);
        }
Exemple #7
0
        public async Task ExceptionDiagnosticAvailable()
        {
            DiagnosticListener diagnosticListener = null;
            var server = TestServer.Create(app =>
            {
                diagnosticListener = app.ApplicationServices.GetRequiredService <DiagnosticListener>();
                app.Run(context =>
                {
                    throw new Exception("Test exception");
                });
            });
            var listener = new TestDiagnosticListener();

            diagnosticListener.SubscribeWithAdapter(listener);
            await Assert.ThrowsAsync <Exception>(() => server.CreateClient().GetAsync("/path"));

            Assert.NotNull(listener.BeginRequest?.HttpContext);
            Assert.Null(listener.EndRequest?.HttpContext);
            Assert.NotNull(listener.UnhandledException?.HttpContext);
            Assert.NotNull(listener.UnhandledException?.Exception);
        }
Exemple #8
0
        public async Task BeginEndDiagnosticAvailable()
        {
            DiagnosticListener diagnosticListener = null;
            var server = TestServer.Create(app =>
            {
                diagnosticListener = app.ApplicationServices.GetRequiredService <DiagnosticListener>();
                app.Run(context =>
                {
                    return(context.Response.WriteAsync("Hello World"));
                });
            });
            var listener = new TestDiagnosticListener();

            diagnosticListener.SubscribeWithAdapter(listener);
            var result = await server.CreateClient().GetStringAsync("/path");

            Assert.Equal("Hello World", result);
            Assert.NotNull(listener.BeginRequest?.HttpContext);
            Assert.NotNull(listener.EndRequest?.HttpContext);
            Assert.Null(listener.UnhandledException);
        }
        public async Task HandledErrorsWriteToDiagnosticWhenUsingExceptionHandler()
        {
            // Arrange
            DiagnosticListener diagnosticListener = null;

            var server = TestServer.Create(app =>
            {
                diagnosticListener = app.ApplicationServices.GetRequiredService <DiagnosticListener>();

                app.UseExceptionHandler("/handle-errors");
                app.Map("/handle-errors", (innerAppBuilder) =>
                {
                    innerAppBuilder.Run(async(httpContext) =>
                    {
                        await httpContext.Response.WriteAsync("Handled error in a custom way.");
                    });
                });
                app.Run(context =>
                {
                    throw new Exception("Test exception");
                });
            });

            var listener = new TestDiagnosticListener();

            diagnosticListener.SubscribeWithAdapter(listener);

            // Act
            await server.CreateClient().GetAsync(string.Empty);

            // Assert
            Assert.NotNull(listener.EndRequest?.HttpContext);
            Assert.Null(listener.HostingUnhandledException?.HttpContext);
            Assert.Null(listener.HostingUnhandledException?.Exception);
            Assert.Null(listener.DiagnosticUnhandledException?.HttpContext);
            Assert.Null(listener.DiagnosticUnhandledException?.Exception);
            Assert.NotNull(listener.DiagnosticHandledException?.HttpContext);
            Assert.NotNull(listener.DiagnosticHandledException?.Exception);
        }
Exemple #10
0
    public async Task NullInfoInCompilationException_ShouldNotThrowExceptionGeneratingExceptionPage(
        List <CompilationFailure> failures)
    {
        // Arrange
        DiagnosticListener diagnosticListener = null;

        using var host = new HostBuilder()
                         .ConfigureWebHost(webHostBuilder =>
        {
            webHostBuilder
            .UseTestServer()
            .Configure(app =>
            {
                diagnosticListener = app.ApplicationServices.GetRequiredService <DiagnosticListener>();
                app.UseDeveloperExceptionPage();
                app.Run(context =>
                {
                    throw new CustomCompilationException(failures);
                });
            });
        }).Build();

        await host.StartAsync();

        var server   = host.GetTestServer();
        var listener = new TestDiagnosticListener();

        diagnosticListener.SubscribeWithAdapter(listener);

        // Act
        await server.CreateClient().GetAsync("/path");

        // Assert
        Assert.NotNull(listener.DiagnosticUnhandledException?.HttpContext);
        Assert.NotNull(listener.DiagnosticUnhandledException?.Exception);
        Assert.Null(listener.DiagnosticHandledException?.HttpContext);
        Assert.Null(listener.DiagnosticHandledException?.Exception);
    }
Exemple #11
0
    private IServiceCollection CreateServices(
        object diagnosticListener,
        HttpContext context,
        params ViewComponentDescriptor[] descriptors)
    {
        var httpContext      = new DefaultHttpContext();
        var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");

        if (diagnosticListener != null)
        {
            diagnosticSource.SubscribeWithAdapter(diagnosticListener);
        }

        var services = new ServiceCollection();

        services.AddSingleton <DiagnosticListener>(diagnosticSource);
        services.AddSingleton <ViewComponentInvokerCache>();
        services.AddSingleton(Options.Create(new MvcViewOptions()));
        services.AddTransient <IViewComponentHelper, DefaultViewComponentHelper>();
        services.AddSingleton <IViewComponentSelector, DefaultViewComponentSelector>();
        services.AddSingleton <IViewComponentDescriptorCollectionProvider, DefaultViewComponentDescriptorCollectionProvider>();
        services.AddSingleton <IViewComponentInvokerFactory, DefaultViewComponentInvokerFactory>();
        services.AddSingleton <ITypeActivatorCache, TypeActivatorCache>();
        services.AddSingleton <IViewComponentActivator, DefaultViewComponentActivator>();
        services.AddSingleton <IViewComponentFactory, DefaultViewComponentFactory>();
        services.AddSingleton <IViewComponentDescriptorProvider>(new FixedSetViewComponentDescriptorProvider(descriptors));
        services.AddSingleton <IModelMetadataProvider, EmptyModelMetadataProvider>();
        services.AddSingleton <ILoggerFactory>(NullLoggerFactory.Instance);
        services.AddSingleton <ITempDataDictionaryFactory, TempDataDictionaryFactory>();
        services.AddSingleton <ITempDataProvider, SessionStateTempDataProvider>();
        services.AddSingleton <TempDataSerializer, DefaultTempDataSerializer>();
        services.AddSingleton <HtmlEncoder, HtmlTestEncoder>();
        services.AddSingleton <IViewBufferScope, TestViewBufferScope>();
        services.AddSingleton <IActionResultExecutor <ViewComponentResult>, ViewComponentResultExecutor>();
        services.AddSingleton <IHttpResponseStreamWriterFactory, TestHttpResponseStreamWriterFactory>();

        return(services);
    }
        public void LogCritical()
        {
            var adapter = AutoFake.Resolve <DiagnosticListenerLoggingAdapter>();
            var source  = new DiagnosticListener("Test");

            using (source.SubscribeWithAdapter(adapter))
            {
                var logger = new DiagnosticLogger(source);

                logger.LogCritical("test");

                A.CallTo(
                    () => Logger.Log(
                        LogLevel.Critical,
                        A <EventId> ._,
                        A <object> ._,
                        A <Exception> ._,
                        A <Func <object, Exception, string> > ._
                        )
                    )
                .MustHaveHappened();
            }
        }
Exemple #13
0
    public async Task UnhandledErrorsWriteToDiagnosticWhenUsingExceptionPage()
    {
        // Arrange
        DiagnosticListener diagnosticListener = null;

        using var host = new HostBuilder()
                         .ConfigureWebHost(webHostBuilder =>
        {
            webHostBuilder
            .UseTestServer()
            .Configure(app =>
            {
                diagnosticListener = app.ApplicationServices.GetRequiredService <DiagnosticListener>();
                app.UseDeveloperExceptionPage();
                app.Run(context =>
                {
                    throw new Exception("Test exception");
                });
            });
        }).Build();

        await host.StartAsync();

        var server   = host.GetTestServer();
        var listener = new TestDiagnosticListener();

        diagnosticListener.SubscribeWithAdapter(listener);

        // Act
        await server.CreateClient().GetAsync("/path");

        // Assert
        Assert.NotNull(listener.DiagnosticUnhandledException?.HttpContext);
        Assert.NotNull(listener.DiagnosticUnhandledException?.Exception);
        Assert.Null(listener.DiagnosticHandledException?.HttpContext);
        Assert.Null(listener.DiagnosticHandledException?.Exception);
    }
        public void Configure(
            IApplicationBuilder app,
            IWebHostEnvironment env,
            ILoggerFactory loggerFactory,
            DiagnosticListener diagnosticListener)
        {
            // Listen for middleware events and log them to the console.
            var listener = new TestDiagnosticListener("/", loggerFactory);

            diagnosticListener.SubscribeWithAdapter(listener);

            app.UseProxySupportIfNecessary(ProxyConfiguration);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapApplicationHealthChecks();
            });
        }
Exemple #15
0
        public void Configure(IApplicationBuilder app, ILoggerFactory factory, DiagnosticListener diagnosticListener)
        {
            // Listen for middleware events and log them to the console.
            var listener = new TestDiagnosticListener();

            diagnosticListener.SubscribeWithAdapter(listener);

            // Build our application pipeline

            // Named via app.UseMiddleware<T>()
            app.UseDeveloperExceptionPage();

            // Anonymous method inline middleware
            app.Use((context, next) =>
            {
                // No-op
                return(next());
            });

            app.Map("/map", subApp =>
            {
                subApp.Run(context =>
                {
                    return(context.Response.WriteAsync("Hello World"));
                });
            });

            // Low level anonymous method inline middleware, named Diagnostics.Middleware.Analysis.Startup+<>c by default
            app.Use(next =>
            {
                return(context =>
                {
                    return next(context);
                });
            });

            app.Map("/throw", throwApp =>
            {
                throwApp.Run(context => { throw new Exception("Application Exception"); });
            });

            // The home page.
            app.Properties["analysis.NextMiddlewareName"] = "HomePage";
            app.Use(async(context, next) =>
            {
                if (context.Request.Path == "/")
                {
                    context.Response.ContentType = "text/html";
                    await context.Response.WriteAsync("<html><body>Welcome to the sample<br><br>\r\n");
                    await context.Response.WriteAsync("Click here to take a side branch: <a href=\"/map/foo\">Map</a><br>\r\n");
                    await context.Response.WriteAsync("Click here to throw an exception: <a href=\"/throw\">Throw</a><br>\r\n");
                    await context.Response.WriteAsync("Click here to for a 404: <a href=\"/404\">404</a><br>\r\n");
                    await context.Response.WriteAsync("</body></html>\r\n");
                    return;
                }
                else
                {
                    await next();
                }
            });

            // Note there's always a default 404 middleware at the end of the pipeline.
        }
Exemple #16
0
        public static void DiagnosticSourceTest()
        {
            #region DiagnosticSource
            var diagnosticListener =
                new DiagnosticListener(DiagnosticStrings.DiagnosticListenerName);

            ////订阅方法一
            //DiagnosticListener.AllListeners.Subscribe(new MyObserver<DiagnosticListener>(listener =>
            //{
            //    //判断发布者的名字
            //    if (listener.Name == DiagnosticStrings.DiagnosticListenerName)
            //    {
            //        //获取订阅信息
            //        listener.Subscribe(new MyObserver<KeyValuePair<string, object>>(listenerData =>
            //        {
            //            Console.WriteLine($"监听名称:{listenerData.Key}");
            //            dynamic data = listenerData.Value;
            //            Console.WriteLine(data.Sql);
            //        }));
            //    }
            //}));

            ////订阅方法二
            DiagnosticListener.AllListeners.Subscribe(new MyObserver <DiagnosticListener>(listener =>
            {
                if (listener.Name == DiagnosticStrings.DiagnosticListenerName)
                {
                    //适配订阅
                    listener.SubscribeWithAdapter(new MyDiagnosticListener());
                }
            }));

            //订阅方法三
            //diagnosticListener.SubscribeWithAdapter(new MyDiagnosticListener());
            diagnosticListener.SubscribeWithAdapter(new SqlBuilderDiagnosticListener(null));

            //发送日志诊断消息
            if (diagnosticListener.IsEnabled(DiagnosticStrings.BeforeExecute) &&
                diagnosticListener.IsEnabled(DiagnosticStrings.AfterExecute) &&
                diagnosticListener.IsEnabled(DiagnosticStrings.ErrorExecute))
            {
                var message = new DiagnosticsMessage
                {
                    Sql        = "select * from table",
                    Parameters = new Dictionary <string, object>
                    {
                        ["key"] = "123"
                    },
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                diagnosticListener.Write(
                    DiagnosticStrings.BeforeExecute,
                    message);

                message.ElapsedMilliseconds = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - message.Timestamp;
                diagnosticListener.Write(
                    DiagnosticStrings.AfterExecute,
                    message);

                message.ElapsedMilliseconds = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - message.Timestamp;
                message.Exception           = new Exception("测试异常");
                diagnosticListener.Write(
                    DiagnosticStrings.ErrorExecute,
                    message);
            }
            #endregion
        }
        public void FindView_WritesDiagnostic_ViewNotFound()
        {
            // Arrange
            var diagnosticSource = new DiagnosticListener("Test");
            var listener = new TestDiagnosticListener();
            diagnosticSource.SubscribeWithAdapter(listener);

            var context = GetActionContext();
            var executor = GetViewExecutor(diagnosticSource);

            var viewName = "myview";
            var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
            viewEngine
                .Setup(e => e.FindPartialView(context, "myview"))
                .Returns(ViewEngineResult.NotFound("myview", new string[] { "location/myview" }));

            var viewResult = new PartialViewResult
            {
                ViewName = viewName,
                ViewEngine = viewEngine.Object,
                ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
                TempData = Mock.Of<ITempDataDictionary>(),
            };

            // Act
            var viewEngineResult = executor.FindView(context, viewResult);

            // Assert
            Assert.False(viewEngineResult.Success);

            Assert.NotNull(listener.ViewNotFound);
            Assert.NotNull(listener.ViewNotFound.ActionContext);
            Assert.NotNull(listener.ViewNotFound.Result);
            Assert.Equal(new string[] { "location/myview" }, listener.ViewNotFound.SearchedLocations);
            Assert.Equal("myview", listener.ViewNotFound.ViewName);
        }
Exemple #18
0
        public async Task WriteAttribute_WritesBeginAndEndEvents_ToDiagnosticSource()
        {
            // Arrange
            var path = "path-to-page";
            var page = CreatePage(p =>
            {
                p.HtmlEncoder = new HtmlTestEncoder();
                p.BeginWriteAttribute("href", "prefix", 0, "suffix", 34, 2);
                p.WriteAttributeValue("prefix", 0, "attr1-value", 8, 14, true);
                p.WriteAttributeValue("prefix2", 22, "attr2", 29, 5, false);
                p.EndWriteAttribute();
            });
            page.Path = path;
            var adapter = new TestDiagnosticListener();
            var diagnosticListener = new DiagnosticListener("Microsoft.AspNet.Mvc.Razor");
            diagnosticListener.SubscribeWithAdapter(adapter);
            page.DiagnosticSource = diagnosticListener;

            // Act
            await page.ExecuteAsync();

            // Assert
            Func<object, TestDiagnosticListener.BeginPageInstrumentationData> assertStartEvent = data =>
            {
                var beginEvent = Assert.IsType<TestDiagnosticListener.BeginPageInstrumentationData>(data);
                Assert.NotNull(beginEvent.HttpContext);
                Assert.Equal(path, beginEvent.Path);

                return beginEvent;
            };

            Action<object> assertEndEvent = data =>
            {
                var endEvent = Assert.IsType<TestDiagnosticListener.EndPageInstrumentationData>(data);
                Assert.NotNull(endEvent.HttpContext);
                Assert.Equal(path, endEvent.Path);
            };

            Assert.Collection(adapter.PageInstrumentationData,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(0, beginEvent.Position);
                    Assert.Equal(6, beginEvent.Length);
                    Assert.True(beginEvent.IsLiteral);
                },
                assertEndEvent,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(0, beginEvent.Position);
                    Assert.Equal(6, beginEvent.Length);
                    Assert.True(beginEvent.IsLiteral);
                },
                assertEndEvent,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(8, beginEvent.Position);
                    Assert.Equal(14, beginEvent.Length);
                    Assert.True(beginEvent.IsLiteral);
                },
                assertEndEvent,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(22, beginEvent.Position);
                    Assert.Equal(7, beginEvent.Length);
                    Assert.True(beginEvent.IsLiteral);
                },
                assertEndEvent,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(29, beginEvent.Position);
                    Assert.Equal(5, beginEvent.Length);
                    Assert.False(beginEvent.IsLiteral);
                },
                assertEndEvent,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(34, beginEvent.Position);
                    Assert.Equal(6, beginEvent.Length);
                    Assert.True(beginEvent.IsLiteral);
                },
                assertEndEvent);
        }
        public async Task ExecuteAsync_WritesDiagnostic()
        {
            // Arrange
            var view = CreateView(async (v) =>
            {
                await v.Writer.WriteAsync("abcd");
            });

            var context = new DefaultHttpContext();
            var memoryStream = new MemoryStream();
            context.Response.Body = memoryStream;

            var actionContext = new ActionContext(
                context,
                new RouteData(),
                new ActionDescriptor());
            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());

            var adapter = new TestDiagnosticListener();

            var diagnosticSource = new DiagnosticListener("Test");
            diagnosticSource.SubscribeWithAdapter(adapter);

            var viewExecutor = CreateViewExecutor(diagnosticSource);

            // Act
            await viewExecutor.ExecuteAsync(
                actionContext,
                view,
                viewData,
                Mock.Of<ITempDataDictionary>(),
                contentType: null,
                statusCode: null);

            // Assert
            Assert.Equal("abcd", Encoding.UTF8.GetString(memoryStream.ToArray()));

            Assert.NotNull(adapter.BeforeView?.View);
            Assert.NotNull(adapter.BeforeView?.ViewContext);
            Assert.NotNull(adapter.AfterView?.View);
            Assert.NotNull(adapter.AfterView?.ViewContext);
        }
        private IServiceCollection CreateServices(
            object diagnosticListener,
            HttpContext context,
            params ViewComponentDescriptor[] descriptors)
        {
            var httpContext = new DefaultHttpContext();
            var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
            if (diagnosticListener != null)
            {
                diagnosticSource.SubscribeWithAdapter(diagnosticListener);
            }

            var services = new ServiceCollection();
            services.AddSingleton<DiagnosticSource>(diagnosticSource);
            services.AddSingleton<ViewComponentInvokerCache>();
            services.AddSingleton<ExpressionTextCache>();
            services.AddSingleton<IOptions<MvcViewOptions>, TestOptionsManager<MvcViewOptions>>();
            services.AddTransient<IViewComponentHelper, DefaultViewComponentHelper>();
            services.AddSingleton<IViewComponentSelector, DefaultViewComponentSelector>();
            services.AddSingleton<IViewComponentDescriptorCollectionProvider, DefaultViewComponentDescriptorCollectionProvider>();
            services.AddSingleton<IViewComponentInvokerFactory, DefaultViewComponentInvokerFactory>();
            services.AddSingleton<ITypeActivatorCache, TypeActivatorCache>();
            services.AddSingleton<IViewComponentActivator, DefaultViewComponentActivator>();
            services.AddSingleton<IViewComponentFactory, DefaultViewComponentFactory>();
            services.AddSingleton<IViewComponentDescriptorProvider>(new FixedSetViewComponentDescriptorProvider(descriptors));
            services.AddSingleton<IModelMetadataProvider, EmptyModelMetadataProvider>();
            services.AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance);
            services.AddSingleton<ITempDataDictionaryFactory, TempDataDictionaryFactory>();
            services.AddSingleton<ITempDataProvider, SessionStateTempDataProvider>();
            services.AddSingleton<HtmlEncoder, HtmlTestEncoder>();
            services.AddSingleton<IViewBufferScope, TestViewBufferScope>();

            return services;
        }
        private RouteContext CreateRouteContext(
            ActionDescriptor actionDescriptor     = null,
            IActionSelector actionSelector        = null,
            IActionInvokerFactory invokerFactory  = null,
            ILoggerFactory loggerFactory          = null,
            IOptions <MvcOptions> optionsAccessor = null,
            object diagnosticListener             = null)
        {
            if (actionDescriptor == null)
            {
                var mockAction = new Mock <ActionDescriptor>();
                actionDescriptor = mockAction.Object;
            }

            if (actionSelector == null)
            {
                var mockActionSelector = new Mock <IActionSelector>();
                mockActionSelector.Setup(a => a.Select(It.IsAny <RouteContext>()))
                .Returns(actionDescriptor);

                actionSelector = mockActionSelector.Object;
            }

            if (invokerFactory == null)
            {
                var mockInvoker = new Mock <IActionInvoker>();
                mockInvoker.Setup(i => i.InvokeAsync())
                .Returns(Task.FromResult(true));

                var mockInvokerFactory = new Mock <IActionInvokerFactory>();
                mockInvokerFactory.Setup(f => f.CreateInvoker(It.IsAny <ActionContext>()))
                .Returns(mockInvoker.Object);

                invokerFactory = mockInvokerFactory.Object;
            }

            if (loggerFactory == null)
            {
                loggerFactory = NullLoggerFactory.Instance;
            }

            if (optionsAccessor == null)
            {
                optionsAccessor = new TestOptionsManager <MvcOptions>();
            }

            var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");

            if (diagnosticListener != null)
            {
                diagnosticSource.SubscribeWithAdapter(diagnosticListener);
            }

            var routingFeature = new RoutingFeature();

            var httpContext = new Mock <HttpContext>();

            httpContext
            .Setup(h => h.RequestServices.GetService(typeof(IActionContextAccessor)))
            .Returns(new ActionContextAccessor());
            httpContext
            .Setup(h => h.RequestServices.GetService(typeof(IActionSelector)))
            .Returns(actionSelector);
            httpContext
            .Setup(h => h.RequestServices.GetService(typeof(IActionInvokerFactory)))
            .Returns(invokerFactory);
            httpContext
            .Setup(h => h.RequestServices.GetService(typeof(ILoggerFactory)))
            .Returns(loggerFactory);
            httpContext
            .Setup(h => h.RequestServices.GetService(typeof(MvcMarkerService)))
            .Returns(new MvcMarkerService());
            httpContext
            .Setup(h => h.RequestServices.GetService(typeof(IOptions <MvcOptions>)))
            .Returns(optionsAccessor);
            httpContext
            .Setup(h => h.RequestServices.GetService(typeof(DiagnosticSource)))
            .Returns(diagnosticSource);
            httpContext
            .Setup(h => h.Features[typeof(IRoutingFeature)])
            .Returns(routingFeature);

            var routeContext = new RouteContext(httpContext.Object);

            routingFeature.RouteData = routeContext.RouteData;
            return(routeContext);
        }
Exemple #22
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, DiagnosticListener diagnosticListener)
        {
            var listener = new ApplicationDiagnosticListener();

            diagnosticListener.SubscribeWithAdapter(listener);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseSession();

            var routeBuilder = new RouteBuilder(app);

            routeBuilder.MapGet("CreateUser", context =>
            {
                var firstName   = context.Request.Query["firstName"];
                var lastName    = context.Request.Query["lastName"];
                var email       = context.Request.Query["email"];
                var password    = context.Request.Query["password"];
                var userService = context.RequestServices.GetService <IUserService>();
                userService.RegisterUser(new UserModel {
                    FirstName = firstName, LastName = lastName, Email = email, Password = password
                });
                return(context.Response.WriteAsync($"User {firstName} {lastName} has been sucessfully created."));
            });
            var newUserRoutes = routeBuilder.Build();

            app.UseRouter(newUserRoutes);

            app.UseWebSockets();
            app.UseCommunicationMiddleware();

            var supportedCultures   = CultureInfo.GetCultures(CultureTypes.AllCultures);
            var localizationOptions = new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("en-US"),
                SupportedCultures     = supportedCultures,
                SupportedUICultures   = supportedCultures
            };

            localizationOptions.RequestCultureProviders.Clear();
            localizationOptions.RequestCultureProviders.Add(new CultureProviderResolverService());

            app.UseRequestLocalization(localizationOptions);

            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "areaRoute",
                                template: "{area:exists}/{controller=Home}/{action=Index}");

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseStatusCodePages("text/plain", "HTTP Error - Status Code: {0}");

            var provider     = app.ApplicationServices;
            var scopeFactory = provider.GetRequiredService <IServiceScopeFactory>();

            using (var scope = scopeFactory.CreateScope())
                using (var context = scope.ServiceProvider.GetRequiredService <GameDbContext>())
                {
                    context.Database.Migrate();
                }
        }
 protected override void OnNext(DiagnosticListener listener, ITracingDiagnosticProcessor diagnosticProcessor)
 {
     listener.SubscribeWithAdapter(diagnosticProcessor);
 }
        private static ViewComponentContext GetViewComponentContext(
            IView view,
            ViewDataDictionary viewData,
            object diagnosticListener = null)
        {
            var diagnosticSource = new DiagnosticListener("Microsoft.AspNet");
            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",
                Type = typeof(object),
                MethodInfo = typeof(object).GetTypeInfo().DeclaredMethods.First()
            };

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

            return viewComponentContext;
        }
Exemple #25
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public async void Configure(IApplicationBuilder app, IHostingEnvironment env, DiagnosticListener diagnosticListener)
        {
            var listener = new WapDiagnosticListener(app);

            diagnosticListener.SubscribeWithAdapter(listener);

            #region register admin branch
            app.Map("/admin", subApp => {
                subApp.UseStaticFiles();
                subApp.UseMvc(
                    routes =>
                {
                    routes.MapRoute(
                        "Admin",
                        $"{{controller=Home}}/{{action=Index}}/{{id?}}",
                        null,
                        null,
                        new { Namespace = "APIGateway.Controllers" });
                });
            });
            #endregion

            #region register diagnostic branch
            app.Map("/diagnostic", subApp => {
                subApp.UseStaticFiles();
                subApp.UseMvc(
                    routes =>
                {
                    routes.MapRoute(
                        "Diagnostic",
                        $"{{controller=Diagnostic}}/{{action=Index}}/{{id?}}",
                        null,
                        null,
                        new { Namespace = "APIGateway.Controllers" });
                });
            });
            app.UseSignalR(routes =>
            {
                routes.MapHub <WapDiagnosticHub>("wapDiagnosticHub");
            });
            #endregion

            #region register diagnostic branch
            app.Map("/logging", subApp => {
                subApp.UseStaticFiles();
                subApp.UseMvc(
                    routes =>
                {
                    routes.MapRoute(
                        "Logging",
                        $"{{controller=Logging}}/{{action=Index}}/{{id?}}",
                        null,
                        null,
                        new { Namespace = "APIGateway.Controllers" });
                });
            });
            app.UseSignalR(routes =>
            {
                routes.MapHub <WapDiagnosticHub>("wapDiagnosticHub");
            });
            #endregion

            await app.UseOcelot();
        }
Exemple #26
0
 public static void AddToolkitDiagnositcs(this DiagnosticListener diagnosticListener)
 {
     diagnosticListener.SubscribeWithAdapter(new ExceptionHandlerDiagnostic());
 }
Exemple #27
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions <RequestLocalizationOptions> requestLocalizationOptions, IServiceProvider serviceProvider, DiagnosticListener diagnosticListener)
        {
            //loggerFactory.AddFile((categoryName, logLevel) => true);

            diagnosticListener.SubscribeWithAdapter(new BookListener());

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseSession();
            app.UseMiddleware <LoggingMiddleware>();
            app.UseRequestLocalization(requestLocalizationOptions.Value);
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseElmPage();
            app.UseElmCapture();

            app.UseSignalR(routes =>
            {
                routes.MapHub <ChatHub>("chat", opt =>
                {
                    opt.Transports = Microsoft.AspNetCore.Sockets.TransportType.LongPolling | Microsoft.AspNetCore.Sockets.TransportType.ServerSentEvents;
                });
                routes.MapHub <TimerHub>("timer", opt =>
                {
                    opt.Transports = Microsoft.AspNetCore.Sockets.TransportType.LongPolling | Microsoft.AspNetCore.Sockets.TransportType.ServerSentEvents;
                });
            });

            TimerCallback callback = (x) => {
                var hub = serviceProvider.GetService <IHubContext <TimerHub> >();
                hub.Clients.All.InvokeAsync("Notify", DateTime.Now);
            };

            //var timer = new Timer(callback);
            //timer.Change(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(10));

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "localizedDefault",
                    template: "{culture:culture}/{controller=Home}/{action=Index}/{id?}",
                    defaults: new { culture = requestLocalizationOptions.Value.DefaultRequestCulture.Culture.Name });

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "NotFound",
                    template: "{*url}",
                    defaults: new { controller = "Home", action = "CatchAll" });
            });
        }
Exemple #28
0
        /*
         * private static void ApiPipeline(IApplicationBuilder app)
         * {
         *  app.Run(async context => {
         *      await context.Response.WriteAsync("Branched to Api Pipeline");
         *  });
         * }
         *
         * private static void WebPipeline(IApplicationBuilder app)
         * {
         *  app.MapWhen(context => {
         *      return context.Request.Query.ContainsKey("usr");
         *  }, UserPipeline);
         *
         *  app.Run(async context => {
         *      await context.Response.WriteAsync("Branched to Web Pipeline");
         *  });
         * }
         *
         * private static void UserPipeline(IApplicationBuilder app)
         * {
         *  app.Run(async context => {
         *      await context.Response.WriteAsync("Branched to User Pipeline");
         *  });
         * }
         */

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DiagnosticListener diagnosticListener)
        {
            /*
             * app.Map("/api", ApiPipeline);
             * app.Map("/web", WebPipeline);
             * app.Use(next => async context => {
             *  await context.Response.WriteAsync("Called Use.");
             *  await next.Invoke(context);
             * });
             *
             * app.Run(async context => {
             *  await context.Response.WriteAsync("Finished with Run");
             * });
             */

            var listener = new ApplicationDiagnosticListener();

            diagnosticListener.SubscribeWithAdapter(listener);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseDeveloperExceptionPage();
                // app.UseExceptionHandler("/Error");
                // app.UseHsts();
            }

            var routeBuilder = new RouteBuilder(app);

            routeBuilder.MapGet("CreateUser", context => {
                var firstName = context.Request.Query["firstName"];
                var lastName  = context.Request.Query["lastName"];
                var email     = context.Request.Query["email"];
                var password  = context.Request.Query["password"];

                var userService = context.RequestServices.GetService <IUserService>();

                userService.RegisterUser(new UserModel {
                    FirstName = firstName, LastName = lastName, Password = password, Email = email, EmailConfirmed = true
                });

                return(context.Response.WriteAsync($"User {firstName} {lastName} has been successfully created."));
            });

            var newUserRoutes = routeBuilder.Build();

            app.UseRouter(newUserRoutes);

            using (StreamReader iisUrlRewriteStreamReader = File.OpenText("Rewrite/IISUrlRewrite.xml"))
            {
                var options = new RewriteOptions().AddIISUrlRewrite(iisUrlRewriteStreamReader); //.AddRewrite("NewUser", "/UserRegistration/Index", false);
                app.UseRewriter(options);
            }

            var supportedCultures   = CultureInfo.GetCultures(CultureTypes.AllCultures);
            var localizationOptions = new RequestLocalizationOptions {
                DefaultRequestCulture = new RequestCulture("en-US"),
                SupportedCultures     = supportedCultures,
                SupportedUICultures   = supportedCultures
            };

            localizationOptions.RequestCultureProviders.Clear();
            localizationOptions.RequestCultureProviders.Add(new CultureProviderResolverService());

            app.UseCookiePolicy();
            app.UseStaticFiles();
            app.UseSession();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseWebSockets();
            app.UseCommunicationMiddleware();
            // app.UseDirectoryBrowser();
            app.UseRequestLocalization(localizationOptions);
            app.UseStatusCodePages("text/plain", "HTTP Error Status Code: {0}");

            /*
             * app.UseSwagger();
             * app.UseSwaggerUI(c => {
             *  c.SwaggerEndpoint("/swagger/v1/swagger.json", "LEARNING ASP.CORE 3.0 V1");
             * });
             */
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapAreaControllerRoute(name: "areas", areaName: "Account", pattern: "Account/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            /*
             * var provider = app.ApplicationServices;
             * var scopeFactory = provider.GetRequiredService<IServiceScopeFactory>();
             *
             * using var scope = scopeFactory.CreateScope();
             * scope.ServiceProvider.GetRequiredService<GameDbContext>()
             *  .Database.Migrate();
             */
        }
Exemple #29
0
        public async Task WriteAttribute_WritesBeginAndEndEvents_ToDiagnosticSource_OnPrefixAndSuffixValues()
        {
            // Arrange
            var path = "some-path";
            var page = CreatePage(p =>
            {
                p.BeginWriteAttribute("href", "prefix", 0, "tail", 7, 0);
                p.EndWriteAttribute();
            });
            page.Path = path;
            var adapter = new TestDiagnosticListener();
            var diagnosticListener = new DiagnosticListener("Microsoft.AspNet.Mvc.Razor");
            diagnosticListener.SubscribeWithAdapter(adapter);
            page.DiagnosticSource = diagnosticListener;

            // Act
            await page.ExecuteAsync();

            // Assert
            Func<object, TestDiagnosticListener.BeginPageInstrumentationData> assertStartEvent = data =>
            {
                var beginEvent = Assert.IsType<TestDiagnosticListener.BeginPageInstrumentationData>(data);
                Assert.NotNull(beginEvent.HttpContext);
                Assert.Equal(path, beginEvent.Path);

                return beginEvent;
            };

            Action<object> assertEndEvent = data =>
            {
                var endEvent = Assert.IsType<TestDiagnosticListener.EndPageInstrumentationData>(data);
                Assert.NotNull(endEvent.HttpContext);
                Assert.Equal(path, endEvent.Path);
            };

            Assert.Collection(adapter.PageInstrumentationData,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(0, beginEvent.Position);
                    Assert.Equal(6, beginEvent.Length);
                    Assert.True(beginEvent.IsLiteral);
                },
                assertEndEvent,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(7, beginEvent.Position);
                    Assert.Equal(4, beginEvent.Length);
                    Assert.True(beginEvent.IsLiteral);
                },
                assertEndEvent);
        }
Exemple #30
0
        public async Task WriteAttribute_WithBoolValue_WritesBeginAndEndEvents_ToDiagnosticSource()
        {
            // Arrange
            var path = "some-path";
            var page = CreatePage(p =>
            {
                p.HtmlEncoder = new HtmlTestEncoder();
                p.BeginWriteAttribute("href", "prefix", 0, "suffix", 10, 1);
                p.WriteAttributeValue("", 6, "true", 6, 4, false);
                p.EndWriteAttribute();
            });

            page.Path = path;
            var adapter            = new TestDiagnosticListener();
            var diagnosticListener = new DiagnosticListener("Microsoft.AspNet.Mvc.Razor");

            diagnosticListener.SubscribeWithAdapter(adapter);
            page.DiagnosticSource = diagnosticListener;

            // Act
            await page.ExecuteAsync();

            // Assert
            Func <object, TestDiagnosticListener.BeginPageInstrumentationData> assertStartEvent = data =>
            {
                var beginEvent = Assert.IsType <TestDiagnosticListener.BeginPageInstrumentationData>(data);
                Assert.NotNull(beginEvent.HttpContext);
                Assert.Equal(path, beginEvent.Path);

                return(beginEvent);
            };

            Action <object> assertEndEvent = data =>
            {
                var endEvent = Assert.IsType <TestDiagnosticListener.EndPageInstrumentationData>(data);
                Assert.NotNull(endEvent.HttpContext);
                Assert.Equal(path, endEvent.Path);
            };

            Assert.Collection(adapter.PageInstrumentationData,
                              data =>
            {
                var beginEvent = assertStartEvent(data);
                Assert.Equal(0, beginEvent.Position);
                Assert.Equal(6, beginEvent.Length);
                Assert.True(beginEvent.IsLiteral);
            },
                              assertEndEvent,
                              data =>
            {
                var beginEvent = assertStartEvent(data);
                Assert.Equal(6, beginEvent.Position);
                Assert.Equal(4, beginEvent.Length);
                Assert.False(beginEvent.IsLiteral);
            },
                              assertEndEvent,
                              data =>
            {
                var beginEvent = assertStartEvent(data);
                Assert.Equal(10, beginEvent.Position);
                Assert.Equal(6, beginEvent.Length);
                Assert.True(beginEvent.IsLiteral);
            },
                              assertEndEvent);
        }
        private RouteContext CreateRouteContext(
            ActionDescriptor actionDescriptor = null,
            IActionSelector actionSelector = null,
            IActionInvokerFactory invokerFactory = null,
            ILoggerFactory loggerFactory = null,
            IOptions<MvcOptions> optionsAccessor = null,
            object diagnosticListener = null)
        {
            if (actionDescriptor == null)
            {
                var mockAction = new Mock<ActionDescriptor>();
                actionDescriptor = mockAction.Object;
            }

            if (actionSelector == null)
            {
                var mockActionSelector = new Mock<IActionSelector>();
                mockActionSelector.Setup(a => a.Select(It.IsAny<RouteContext>()))
                    .Returns(actionDescriptor);

                actionSelector = mockActionSelector.Object;
            }

            if (invokerFactory == null)
            {
                var mockInvoker = new Mock<IActionInvoker>();
                mockInvoker.Setup(i => i.InvokeAsync())
                    .Returns(Task.FromResult(true));

                var mockInvokerFactory = new Mock<IActionInvokerFactory>();
                mockInvokerFactory.Setup(f => f.CreateInvoker(It.IsAny<ActionContext>()))
                    .Returns(mockInvoker.Object);

                invokerFactory = mockInvokerFactory.Object;
            }

            if (loggerFactory == null)
            {
                loggerFactory = NullLoggerFactory.Instance;
            }

            if (optionsAccessor == null)
            {
                optionsAccessor = new TestOptionsManager<MvcOptions>();
            }

            var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
            if (diagnosticListener != null)
            {
                diagnosticSource.SubscribeWithAdapter(diagnosticListener);
            }

            var routingFeature = new RoutingFeature();

            var httpContext = new Mock<HttpContext>();
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(IActionContextAccessor)))
                .Returns(new ActionContextAccessor());
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(IActionSelector)))
                .Returns(actionSelector);
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(IActionInvokerFactory)))
                .Returns(invokerFactory);
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(ILoggerFactory)))
                .Returns(loggerFactory);
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(MvcMarkerService)))
                .Returns(new MvcMarkerService());
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(IOptions<MvcOptions>)))
                .Returns(optionsAccessor);
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(DiagnosticSource)))
                .Returns(diagnosticSource);
            httpContext
                .Setup(h => h.Features[typeof(IRoutingFeature)])
                .Returns(routingFeature);

            var routeContext = new RouteContext(httpContext.Object);
            routingFeature.RouteData = routeContext.RouteData;
            return routeContext;
        }
Exemple #32
0
        private MvcRouteHandler CreateMvcRouteHandler(
            ActionDescriptor actionDescriptor = null,
            IActionSelector actionSelector = null,
            IActionInvokerFactory invokerFactory = null,
            ILoggerFactory loggerFactory = null,
            object diagnosticListener = null)
        {
            var actionContextAccessor = new ActionContextAccessor();

            if (actionDescriptor == null)
            {
                var mockAction = new Mock<ActionDescriptor>();
                actionDescriptor = mockAction.Object;
            }

            if (actionSelector == null)
            {
                var mockActionSelector = new Mock<IActionSelector>();
                mockActionSelector
                    .Setup(a => a.SelectCandidates(It.IsAny<RouteContext>()))
                    .Returns(new ActionDescriptor[] { actionDescriptor });

                mockActionSelector
                    .Setup(a => a.SelectBestCandidate(It.IsAny<RouteContext>(), It.IsAny<IReadOnlyList<ActionDescriptor>>()))
                    .Returns(actionDescriptor);
                actionSelector = mockActionSelector.Object;
            }

            if (loggerFactory == null)
            {
                loggerFactory = NullLoggerFactory.Instance;
            }

            var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
            if (diagnosticListener != null)
            {
                diagnosticSource.SubscribeWithAdapter(diagnosticListener);
            }

            if (invokerFactory == null)
            {
                var mockInvoker = new Mock<IActionInvoker>();
                mockInvoker.Setup(i => i.InvokeAsync())
                    .Returns(Task.FromResult(true));

                var mockInvokerFactory = new Mock<IActionInvokerFactory>();
                mockInvokerFactory.Setup(f => f.CreateInvoker(It.IsAny<ActionContext>()))
                    .Returns(mockInvoker.Object);

                invokerFactory = mockInvokerFactory.Object;
            }

            return new MvcRouteHandler(
                invokerFactory,
                actionSelector,
                diagnosticSource,
                loggerFactory,
                actionContextAccessor);
        }
        private static ViewComponentContext GetViewComponentContext(IView view, ViewDataDictionary viewData, object diagnosticListener = null)
        {
            var diagnosticSource = new DiagnosticListener("Microsoft.AspNet");
            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(new HttpContextAccessor(), new SessionStateTempDataProvider()),
                TextWriter.Null,
                new HtmlHelperOptions());

            var viewComponentDescriptor = new ViewComponentDescriptor()
            {
                Type = typeof(object),
            };

            var viewComponentContext = new ViewComponentContext(
                viewComponentDescriptor,
                new object[0],
                viewContext,
                TextWriter.Null);

            return viewComponentContext;
        }