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);
        }
Exemple #2
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);
        }
        public VocabTermTests(ITestOutputHelper output)
        {
            this.output = output;
            _listener = new DiagnosticListener("Testing");
            _listener.Subscribe(new ConsoleLogger(this.output));
            JsonStreamingParser.DiagSource = _listener;

        }
 private static void ScheduleLogResponse(DiagnosticListener diagnosticListener, Task<HttpResponseMessage> responseTask, Guid loggingRequestId)
 {
     responseTask.ContinueWith(
         t =>
         {
             if (!t.IsFaulted &&
                 !t.IsCanceled)
             {
                 LogHttpResponseCore(diagnosticListener, t.Result, loggingRequestId);
             }
         },
         TaskScheduler.Default);
 }
        public OperationNameTelemetryInitializer(IHttpContextAccessor httpContextAccessor, DiagnosticListener telemetryListener) 
            : base(httpContextAccessor)
        {
            if (telemetryListener == null)
            {
                throw new ArgumentNullException("telemetryListener");
            }

            if (telemetryListener != null)
            {
                telemetryListener.SubscribeWithAdapter(this);
            }
        }
        private static Guid LogHttpRequestCore(DiagnosticListener diagnosticListener, HttpRequestMessage request)
        {
            Guid loggingRequestId = Guid.NewGuid();
            long timestamp = Stopwatch.GetTimestamp();

            diagnosticListener.Write(
                HttpHandlerLoggingStrings.RequestWriteName,
                new
                {
                    Request = request,
                    LoggingRequestId = loggingRequestId,
                    Timestamp = timestamp
                }
            );

            return loggingRequestId;
        }
        private static void LogHttpResponseCore(DiagnosticListener diagnosticListener, HttpResponseMessage response, Guid loggingRequestId)
        {
            // An empty loggingRequestId signifies that the request was not logged, so do
            // not attempt to log response.
            if (loggingRequestId != Guid.Empty)
            {
                long timestamp = Stopwatch.GetTimestamp();

                diagnosticListener.Write(
                    HttpHandlerLoggingStrings.ResponseWriteName,
                    new
                    {
                        Response = response,
                        LoggingRequestId = loggingRequestId,
                        TimeStamp = timestamp
                    }
                );
            }
        }
        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 OperationNameTelemetryInitializer(contextAccessor, telemetryListener);
            telemetryListener.Write(OperationNameTelemetryInitializer.BeforeActionNotificationName,
                new { httpContext = contextAccessor.HttpContext, routeData = actionContext.RouteData });

            var telemetry = new EventTelemetry();
            initializer.Initialize(telemetry);

            Assert.Equal("GET account/login", telemetry.Context.Operation.Name);
        }
Exemple #9
0
        public void ActivityIsStoppedDuringUnhandledExceptionCall()
        {
            var diagnosticListener = new DiagnosticListener("DummySource");
            var hostingApplication = CreateApplication(out var features, diagnosticListener: diagnosticListener);

            bool endCalled = false;

            diagnosticListener.Subscribe(new CallbackDiagnosticListener(pair =>
            {
                if (pair.Key == "Microsoft.AspNetCore.Hosting.HttpRequestIn.Stop")
                {
                    endCalled = true;
                    Assert.NotNull(Activity.Current);
                    Assert.True(Activity.Current.Duration > TimeSpan.Zero);
                    Assert.Equal("Microsoft.AspNetCore.Hosting.HttpRequestIn", Activity.Current.OperationName);
                    AssertProperty <HttpContext>(pair.Value, "HttpContext");
                }
            }));

            var context = hostingApplication.CreateContext(features);

            hostingApplication.DisposeContext(context, new Exception());
            Assert.True(endCalled);
        }
Exemple #10
0
        public void BasicIsEnabled()
        {
            using (DiagnosticListener listener = new DiagnosticListener("TestingBasicIsEnabled"))
            {
                DiagnosticSource source = listener;
                var result = new List <KeyValuePair <string, object> >();

                bool seenUninteresting       = false;
                bool seenStructPayload       = false;
                Predicate <string> predicate = delegate(string name)
                {
                    if (name == "Uninteresting")
                    {
                        seenUninteresting = true;
                    }
                    if (name == "StructPayload")
                    {
                        seenStructPayload = true;
                    }

                    return(name == "StructPayload");
                };

                // Assert.False(listener.IsEnabled());  Since other things might turn on all DiagnosticSources, we can't ever test that it is not enabled.
                using (listener.Subscribe(new ObserverToList <TelemData>(result), predicate))
                {
                    Assert.False(source.IsEnabled("Uninteresting"));
                    Assert.False(source.IsEnabled("Uninteresting", "arg1", "arg2"));
                    Assert.True(source.IsEnabled("StructPayload"));
                    Assert.True(source.IsEnabled("StructPayload", "arg1", "arg2"));
                    Assert.True(seenUninteresting);
                    Assert.True(seenStructPayload);
                    Assert.True(listener.IsEnabled());
                }
            }
        }
Exemple #11
0
        public void GetTraces_ReturnsTraces()
        {
            var listener = new DiagnosticListener("test");
            var option   = new TraceEndpointOptions();

            var obs     = new TraceDiagnosticObserver(option);
            var current = new Activity("Microsoft.AspNetCore.Hosting.HttpRequestIn");

            current.Start();

            for (var i = 0; i < 200; i++)
            {
                var context = CreateRequest();
                obs.ProcessEvent("Microsoft.AspNetCore.Hosting.HttpRequestIn.Stop", new { HttpContext = context });
            }

            Assert.Equal(option.Capacity, obs._queue.Count);
            var traces = obs.GetTraces();

            Assert.Equal(option.Capacity, traces.Count);
            Assert.Equal(option.Capacity, obs._queue.Count);

            listener.Dispose();
        }
        public void InitializeSortsParameters()
        {
            var actionContext = new ActionContext();

            actionContext.RouteData = new RouteData();
            actionContext.RouteData.Values.Add("controller", "account");
            actionContext.RouteData.Values.Add("action", "login");
            actionContext.RouteData.Values.Add("parameterZ", "myName1");
            actionContext.RouteData.Values.Add("parameterA", "myName2");
            actionContext.RouteData.Values.Add("parameterN", "myName1");

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

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

            telemetryListener.Subscribe(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 [parameterA/parameterN/parameterZ]", telemetry.Name);
        }
Exemple #13
0
        public void InitializeSetsTelemetryOperationNameToControllerAndActionAndParameterFromActionContext()
        {
            var actionContext = new ActionContext();

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

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

            var telemetryListener = new DiagnosticListener(TestListenerName);

            using (var listener = CreateHostingListener(AspNetCoreMajorVersion.One))
            {
                telemetryListener.Subscribe(listener);
                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 [parameter]", telemetry.Name);
        }
        private bool ShouldSubscribe(DiagnosticListener diagnosticListener)
        {
            if (!diagnosticListener.Name.EndsWith(ActivitySuffix))
            {
                return(false);
            }

            var noSuffixName = diagnosticListener.Name.Substring(0, diagnosticListener.Name.Length - ActivitySuffix.Length);

            foreach (var category in _categories)
            {
                if (category == noSuffixName)
                {
                    return(true);
                }

                if (category.EndsWith("*") && noSuffixName.StartsWith(category.Substring(0, category.Length - 1)))
                {
                    return(true);
                }
            }

            return(false);
        }
        private static ServiceProvider BuildProvider()
        {
            var services     = new ServiceCollection();
            var fileProvider = new PhysicalFileProvider(Path.GetDirectoryName(typeof(HtmlRazorReportWriter).Assembly.Location));

#if NETSTANDARD2_0
            services.AddSingleton <IHostingEnvironment>(new HostingEnvironment
            {
                ApplicationName     = Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty,
                WebRootFileProvider = fileProvider,
            });

            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.FileProviders.Clear();
                options.FileProviders.Add(fileProvider);
            });
#endif

            var listener = new DiagnosticListener("Microsoft.AspNetCore.Mvc.Razor");

            services.AddSingleton <DiagnosticSource>(listener);

#if NETCOREAPP3_1
            services.AddSingleton <DiagnosticListener>(listener);
#endif

            services.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();
            services.AddLogging();
            services
            .AddMvc()
            .ConfigureApplicationPartManager(partsManager => ConfigureRazorViews(partsManager, fileProvider));

            services.AddTransient <RazorViewToStringRenderer>();
            return(services.BuildServiceProvider());
        }
Exemple #16
0
 private void WirteDiagnosticBefore(TransportMessage message)
 {
     if (!AppConfig.ServerOptions.DisableDiagnostic)
     {
         RpcContext.GetContext().SetAttachment("TraceId", message.Id);
         var diagnosticListener  = new DiagnosticListener(DiagnosticListenerExtensions.DiagnosticListenerName);
         var remoteInvokeMessage = message.GetContent <HttpMessage>();
         diagnosticListener.WriteTransportBefore(TransportType.Rest, new TransportEventData(new DiagnosticMessage
         {
             Content     = message.Content,
             ContentType = message.ContentType,
             Id          = message.Id,
             MessageName = remoteInvokeMessage.RoutePath
         }, TransportType.Rest.ToString(),
                                                                                            message.Id,
                                                                                            RpcContext.GetContext().GetAttachment("RemoteIpAddress")?.ToString()));
     }
     else
     {
         var parameters = RpcContext.GetContext().GetContextParameters();
         parameters.TryRemove("RemoteIpAddress", out object value);
         RpcContext.GetContext().SetContextParameters(parameters);
     }
 }
Exemple #17
0
        protected ViewExecutor(
            IHttpResponseStreamWriterFactory writerFactory,
            ICompositeViewEngine viewEngine,
            DiagnosticListener diagnosticListener)
        {
            if (writerFactory == null)
            {
                throw new ArgumentNullException(nameof(writerFactory));
            }

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

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

            WriterFactory      = writerFactory;
            ViewEngine         = viewEngine;
            DiagnosticListener = diagnosticListener;
        }
Exemple #18
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 <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);
        }
        public void EventHubsSuccessfulSendIsHandledW3COff()
        {
            Activity.DefaultIdFormat      = ActivityIdFormat.Hierarchical;
            Activity.ForceDefaultIdFormat = true;
            using (var listener = new DiagnosticListener("Microsoft.Azure.EventHubs"))
                using (var module = new DependencyTrackingTelemetryModule())
                {
                    module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.EventHubs");
                    module.Initialize(this.configuration);

                    Activity sendActivity   = null;
                    Activity parentActivity = new Activity("parent").AddBaggage("k1", "v1").Start();
                    var      telemetry      = this.TrackOperation <DependencyTelemetry>(
                        listener,
                        "Microsoft.Azure.EventHubs.Send",
                        TaskStatus.RanToCompletion,
                        null,
                        () => sendActivity = Activity.Current);

                    Assert.IsNotNull(telemetry);
                    Assert.AreEqual("Send", telemetry.Name);
                    Assert.AreEqual(RemoteDependencyConstants.AzureEventHubs, telemetry.Type);
                    Assert.AreEqual("sb://eventhubname.servicebus.windows.net/ | ehname", telemetry.Target);
                    Assert.IsTrue(telemetry.Success.Value);

                    Assert.AreEqual(parentActivity.Id, telemetry.Context.Operation.ParentId);
                    Assert.AreEqual(parentActivity.RootId, telemetry.Context.Operation.Id);
                    Assert.AreEqual(sendActivity.Id, telemetry.Id);

                    Assert.AreEqual("v1", telemetry.Properties["k1"]);
                    Assert.AreEqual("eventhubname.servicebus.windows.net", telemetry.Properties["peer.hostname"]);
                    Assert.AreEqual("ehname", telemetry.Properties["eh.event_hub_name"]);
                    Assert.AreEqual("SomePartitionKeyHere", telemetry.Properties["eh.partition_key"]);
                    Assert.AreEqual("EventHubClient1(ehname)", telemetry.Properties["eh.client_id"]);
                }
        }
Exemple #20
0
 public PageActionInvokerProvider(
     IPageLoader loader,
     IPageFactoryProvider pageFactoryProvider,
     IPageModelFactoryProvider modelFactoryProvider,
     IRazorPageFactoryProvider razorPageFactoryProvider,
     IActionDescriptorCollectionProvider collectionProvider,
     IEnumerable <IFilterProvider> filterProviders,
     ParameterBinder parameterBinder,
     IModelMetadataProvider modelMetadataProvider,
     IModelBinderFactory modelBinderFactory,
     ITempDataDictionaryFactory tempDataFactory,
     IOptions <MvcOptions> mvcOptions,
     IOptions <HtmlHelperOptions> htmlHelperOptions,
     IPageHandlerMethodSelector selector,
     DiagnosticListener diagnosticListener,
     ILoggerFactory loggerFactory,
     IActionResultTypeMapper mapper)
 {
     _loader = loader;
     _pageFactoryProvider      = pageFactoryProvider;
     _modelFactoryProvider     = modelFactoryProvider;
     _modelBinderFactory       = modelBinderFactory;
     _razorPageFactoryProvider = razorPageFactoryProvider;
     _collectionProvider       = collectionProvider;
     _filterProviders          = filterProviders.ToArray();
     _valueProviderFactories   = mvcOptions.Value.ValueProviderFactories.ToArray();
     _parameterBinder          = parameterBinder;
     _modelMetadataProvider    = modelMetadataProvider;
     _tempDataFactory          = tempDataFactory;
     _mvcOptions         = mvcOptions.Value;
     _htmlHelperOptions  = htmlHelperOptions.Value;
     _selector           = selector;
     _diagnosticListener = diagnosticListener;
     _logger             = loggerFactory.CreateLogger <PageActionInvoker>();
     _mapper             = mapper;
 }
Exemple #21
0
        private IServiceCollection ConfigureDefaultServices()
        {
            var           services     = new ServiceCollection();
            IFileProvider fileProvider = new PhysicalFileProvider(_root);

            services.AddSingleton <IHostingEnvironment>(new HostingEnvironment
            {
                ApplicationName     = Assembly.GetEntryAssembly().GetName().Name,
                WebRootFileProvider = fileProvider,
            });
            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.FileProviders.Clear();
                options.FileProviders.Add(fileProvider);
            });
            var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");

            services.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();
            services.AddSingleton <DiagnosticSource>(diagnosticSource);
            services.AddLogging();
            services.AddMvc();
            services.AddTransient <OfficialRazorViewToStringRenderer>();
            return(services);
        }
        public void ServiceBusBadStatusHanding()
        {
            using (var module = new DependencyTrackingTelemetryModule())
            {
                module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.ServiceBus");
                module.Initialize(this.configuration);

                DiagnosticListener listener = new DiagnosticListener("Microsoft.Azure.ServiceBus");

                Activity parentActivity = new Activity("parent").AddBaggage("k1", "v1").Start();
                var      telemetry      = this.TrackOperation <DependencyTelemetry>(listener, "Microsoft.Azure.ServiceBus.Send", TaskStatus.Faulted);

                Assert.IsNotNull(telemetry);
                Assert.AreEqual("Send", telemetry.Name);
                Assert.AreEqual(RemoteDependencyConstants.AzureServiceBus, telemetry.Type);
                Assert.AreEqual("sb://queuename.myservicebus.com/ | queueName", telemetry.Target);
                Assert.IsFalse(telemetry.Success.Value);

                Assert.AreEqual(parentActivity.Id, telemetry.Context.Operation.ParentId);
                Assert.AreEqual(parentActivity.RootId, telemetry.Context.Operation.Id);
                Assert.AreEqual("v1", telemetry.Properties["k1"]);
                Assert.AreEqual("messageId", telemetry.Properties["MessageId"]);
            }
        }
        public override void OnEvent(KeyValuePair <string, object> evnt, DiagnosticListener ignored)
        {
            Activity currentActivity = Activity.Current;

            switch (evnt.Key)
            {
            case "Microsoft.Azure.EventHubs.Send.Start":
            case "Microsoft.Azure.EventHubs.Receive.Start":

                // As a first step in supporting W3C protocol in ApplicationInsights,
                // we want to generate Activity Ids in the W3C compatible format.
                // While .NET changes to Activity are pending, we want to ensure trace starts with W3C compatible Id
                // as early as possible, so that everyone has a chance to upgrade and have compatibility with W3C systems once they arrive.
                // So if there is no parent Activity (i.e. this request has happened in the background, without parent scope), we'll override
                // the current Activity with the one with properly formatted Id. This workaround should go away
                // with W3C support on .NET https://github.com/dotnet/corefx/issues/30331 (TODO)
                if (currentActivity.Parent == null && currentActivity.ParentId == null)
                {
                    currentActivity.UpdateParent(StringUtilities.GenerateTraceId());
                }

                break;

            case "Microsoft.Azure.EventHubs.Send.Stop":
            case "Microsoft.Azure.EventHubs.Receive.Stop":
                // If we started auxiliary Activity before to override the Id with W3C compatible one,
                // now it's time to set end time on it
                if (currentActivity.Duration == TimeSpan.Zero)
                {
                    currentActivity.SetEndTime(DateTime.UtcNow);
                }

                this.OnDependency(evnt.Key, evnt.Value, currentActivity);
                break;
            }
        }
        /// <summary>
        /// Attempts to find the <see cref="IView"/> associated with <paramref name="viewResult"/>.
        /// </summary>
        /// <param name="actionContext">The <see cref="ActionContext"/> associated with the current request.</param>
        /// <param name="viewResult">The <see cref="PartialViewResult"/>.</param>
        /// <returns>A <see cref="ViewEngineResult"/>.</returns>
        public virtual ViewEngineResult FindView(ActionContext actionContext, PartialViewResult viewResult)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException(nameof(actionContext));
            }

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

            var viewEngine = viewResult.ViewEngine ?? ViewEngine;
            var viewName   = viewResult.ViewName ?? GetActionName(actionContext);

            var stopwatch = ValueStopwatch.StartNew();

            var result         = viewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: false);
            var originalResult = result;

            if (!result.Success)
            {
                result = viewEngine.FindView(actionContext, viewName, isMainPage: false);
            }

            Logger.PartialViewResultExecuting(result.ViewName);
            if (!result.Success)
            {
                if (originalResult.SearchedLocations.Any())
                {
                    if (result.SearchedLocations.Any())
                    {
                        // Return a new ViewEngineResult listing all searched locations.
                        var locations = new List <string>(originalResult.SearchedLocations);
                        locations.AddRange(result.SearchedLocations);
                        result = ViewEngineResult.NotFound(viewName, locations);
                    }
                    else
                    {
                        // GetView() searched locations but FindView() did not. Use first ViewEngineResult.
                        result = originalResult;
                    }
                }
            }

            if (result.Success)
            {
                DiagnosticListener.ViewFound(
                    actionContext,
                    isMainPage: false,
                    viewResult: viewResult,
                    viewName: viewName,
                    view: result.View);

                Logger.PartialViewFound(result.View, stopwatch.GetElapsedTime());
            }
            else
            {
                DiagnosticListener.ViewNotFound(
                    actionContext,
                    isMainPage: false,
                    viewResult: viewResult,
                    viewName: viewName,
                    searchedLocations: result.SearchedLocations);

                Logger.PartialViewNotFound(viewName, result.SearchedLocations);
            }

            return(result);
        }
Exemple #25
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);
        }
        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);
        }
        public void TestShortcutKeywords()
        {
            using (var eventSourceListener = new TestDiagnosticSourceEventListener())
            // These are look-alikes for the real ones.  
            using (var aspNetCoreSource = new DiagnosticListener("Microsoft.AspNetCore"))
            using (var entityFrameworkCoreSource = new DiagnosticListener("Microsoft.EntityFrameworkCore"))
            {
                // These are from DiagnosticSourceEventListener.  
                var Messages = (EventKeywords)0x1;
                var Events = (EventKeywords)0x2;
                var AspNetCoreHosting = (EventKeywords)0x1000;
                var EntityFrameworkCoreCommands = (EventKeywords)0x2000;

                // Turn on listener using just the keywords 
                eventSourceListener.Enable(null, Messages | Events | AspNetCoreHosting | EntityFrameworkCoreCommands);

                Assert.Equal(0, eventSourceListener.EventCount);

                // Start a ASP.NET Request
                aspNetCoreSource.Write("Microsoft.AspNetCore.Hosting.BeginRequest",
                    new
                    {
                        httpContext = new
                        {
                            Request = new
                            {
                                Method = "Get",
                                Host = "MyHost",
                                Path = "MyPath",
                                QueryString = "MyQuery"
                            }
                        }
                    });
                // Check that the morphs work as expected.  
                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("Activity1Start", eventSourceListener.LastEvent.EventSourceEventName);
                Assert.Equal("Microsoft.AspNetCore", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("Microsoft.AspNetCore.Hosting.BeginRequest", eventSourceListener.LastEvent.EventName);
                Assert.True(4 <= eventSourceListener.LastEvent.Arguments.Count);
                Debug.WriteLine("Arg Keys = " + string.Join(" ", eventSourceListener.LastEvent.Arguments.Keys));
                Debug.WriteLine("Arg Values = " + string.Join(" ", eventSourceListener.LastEvent.Arguments.Values));
                Assert.Equal("Get", eventSourceListener.LastEvent.Arguments["Method"]);
                Assert.Equal("MyHost", eventSourceListener.LastEvent.Arguments["Host"]);
                Assert.Equal("MyPath", eventSourceListener.LastEvent.Arguments["Path"]);
                Assert.Equal("MyQuery", eventSourceListener.LastEvent.Arguments["QueryString"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                // Start a SQL command 
                entityFrameworkCoreSource.Write("Microsoft.EntityFrameworkCore.BeforeExecuteCommand",
                    new
                    {
                        Command = new
                        {
                            Connection = new
                            {
                                DataSource = "MyDataSource",
                                Database = "MyDatabase",
                            },
                            CommandText = "MyCommand"
                        }
                    });
                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("Activity2Start", eventSourceListener.LastEvent.EventSourceEventName);
                Assert.Equal("Microsoft.EntityFrameworkCore", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("Microsoft.EntityFrameworkCore.BeforeExecuteCommand", eventSourceListener.LastEvent.EventName);
                Assert.True(3 <= eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("MyDataSource", eventSourceListener.LastEvent.Arguments["DataSource"]);
                Assert.Equal("MyDatabase", eventSourceListener.LastEvent.Arguments["Database"]);
                Assert.Equal("MyCommand", eventSourceListener.LastEvent.Arguments["CommandText"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                // Stop the SQL command 
                entityFrameworkCoreSource.Write("Microsoft.EntityFrameworkCore.AfterExecuteCommand", null);
                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("Activity2Stop", eventSourceListener.LastEvent.EventSourceEventName);
                Assert.Equal("Microsoft.EntityFrameworkCore", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("Microsoft.EntityFrameworkCore.AfterExecuteCommand", eventSourceListener.LastEvent.EventName);
                eventSourceListener.ResetEventCountAndLastEvent();

                // Stop the ASP.NET reqeust.  
                aspNetCoreSource.Write("Microsoft.AspNetCore.Hosting.EndRequest", null);
                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("Activity1Stop", eventSourceListener.LastEvent.EventSourceEventName);
                Assert.Equal("Microsoft.AspNetCore", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("Microsoft.AspNetCore.Hosting.EndRequest", eventSourceListener.LastEvent.EventName);
                eventSourceListener.ResetEventCountAndLastEvent();
            }
        }
        public void TestMessages()
        {
            using (var eventSourceListener = new TestDiagnosticSourceEventListener())
            using (var diagnosticSourceListener = new DiagnosticListener("TestMessagesSource"))
            {
                Assert.Equal(0, eventSourceListener.EventCount);

                // This is just to make debugging easier.  
                var messages = new List<string>();

                eventSourceListener.OtherEventWritten += delegate (EventWrittenEventArgs evnt)
                {
                    if (evnt.EventName == "Message")
                    {
                        var message = (string)evnt.Payload[0];
                        messages.Add(message);
                    }
                };

                // This has a syntax error in the Url case, so it should be ignored.  
                eventSourceListener.Enable("TestMessagesSource/TestEvent1:-cls.Url");
                Assert.Equal(0, eventSourceListener.EventCount);
                Assert.True(3 <= messages.Count);
            }
        }
        public void TestNoImplicitTransforms()
        {
            using (var eventSourceListener = new TestDiagnosticSourceEventListener())
            using (var diagnosticSourceListener = new DiagnosticListener("TestNoImplicitTransformsSource"))
            {
                Assert.Equal(0, eventSourceListener.EventCount);

                // use the - prefix to suppress the implicit properties.  Thus you should only get propStr and Url.  
                eventSourceListener.Enable("TestNoImplicitTransformsSource/TestEvent1:-propStr;cls.Url");

                /***************************************************************************************/
                // Emit an event that matches the first pattern. 
                MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
                if (diagnosticSourceListener.IsEnabled("TestEvent1"))
                    diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val, propStr2 = "there" });

                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("TestNoImplicitTransformsSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
                Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]);
                Assert.Equal("MyUrl", eventSourceListener.LastEvent.Arguments["Url"]);
                eventSourceListener.ResetEventCountAndLastEvent();
            }
        }
 public BadRequestEventListener(DiagnosticListener diagnosticListener, Action <KeyValuePair <string, object> > callback)
 {
     _subscription = diagnosticListener.Subscribe(this, IsEnabled);
     _callback     = callback;
 }
        private PartialViewResultExecutor GetViewExecutor(DiagnosticSource diagnosticSource = null)
        {
            if (diagnosticSource == null)
            {
                diagnosticSource = new DiagnosticListener("Test");
            }

            var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
            viewEngine
                .Setup(e => e.FindPartialView(It.IsAny<ActionContext>(), It.IsAny<string>()))
                .Returns<ActionContext, string>((_, name) => ViewEngineResult.Found(name, Mock.Of<IView>()));

            var options = new TestOptionsManager<MvcViewOptions>();
            options.Value.ViewEngines.Add(viewEngine.Object);

            var viewExecutor = new PartialViewResultExecutor(
                options,
                new TestHttpResponseStreamWriterFactory(),
                new CompositeViewEngine(options),
                diagnosticSource,
                NullLoggerFactory.Instance);

            return viewExecutor;
        }
        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;
        }
        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);
        }
        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;
        }
        private ViewResultExecutor GetViewExecutor(DiagnosticListener diagnosticSource = null)
        {
            if (diagnosticSource == null)
            {
                diagnosticSource = new DiagnosticListener("Test");
            }

            var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
            viewEngine
                .Setup(e => e.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ true))
                .Returns<string, string, bool>(
                    (path, name, partial) => ViewEngineResult.NotFound(name, Enumerable.Empty<string>()));
            viewEngine
                .Setup(e => e.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ true))
                .Returns<ActionContext, string, bool>(
                    (context, name, partial) => ViewEngineResult.Found(name, Mock.Of<IView>()));

            var options = new TestOptionsManager<MvcViewOptions>();
            options.Value.ViewEngines.Add(viewEngine.Object);

            var viewExecutor = new ViewResultExecutor(
                options,
                new TestHttpResponseStreamWriterFactory(),
                new CompositeViewEngine(options),
                new TempDataDictionaryFactory(new SessionStateTempDataProvider()),
                diagnosticSource,
                NullLoggerFactory.Instance);

            return viewExecutor;
        }
        private ViewExecutor CreateViewExecutor(DiagnosticListener diagnosticSource = null)
        {
            if (diagnosticSource == null)
            {
                diagnosticSource = new DiagnosticListener("Test");
            }

            return new ViewExecutor(
                new TestOptionsManager<MvcViewOptions>(),
                new TestHttpResponseStreamWriterFactory(),
                new Mock<ICompositeViewEngine>(MockBehavior.Strict).Object,
                new TempDataDictionaryFactory(new SessionStateTempDataProvider()),
                diagnosticSource);
        }
Exemple #37
0
        public OperationNameTelemetryInitializer(IHttpContextAccessor httpContextAccessor, DiagnosticListener telemetryListener)
            : base(httpContextAccessor)
        {
            if (telemetryListener == null)
            {
                throw new ArgumentNullException("telemetryListener");
            }

            if (telemetryListener != null)
            {
                telemetryListener.SubscribeWithAdapter(this);
            }
        }
        private IServiceCollection BuildHostingServices()
        {
            // Apply the configuration settings
            var configuration = _config ?? WebApplicationConfiguration.GetDefault();

            var mergedConfiguration = new ConfigurationBuilder()
                                .Add(new IncludedConfigurationProvider(configuration))
                                .AddInMemoryCollection(_settings)
                                .Build();

            _config = mergedConfiguration;
            _options = new WebApplicationOptions(_config);

            var services = new ServiceCollection();
            services.AddSingleton(_hostingEnvironment);
            services.AddSingleton(_loggerFactory);

            services.AddTransient<IStartupLoader, StartupLoader>();

            services.AddTransient<IServerLoader, ServerLoader>();
            services.AddTransient<IApplicationBuilderFactory, ApplicationBuilderFactory>();
            services.AddTransient<IHttpContextFactory, HttpContextFactory>();
            services.AddLogging();
            services.AddOptions();

            var diagnosticSource = new DiagnosticListener("Microsoft.AspNet");
            services.AddSingleton<DiagnosticSource>(diagnosticSource);
            services.AddSingleton<DiagnosticListener>(diagnosticSource);

            // Conjure up a RequestServices
            services.AddTransient<IStartupFilter, AutoRequestServicesStartupFilter>();

            var defaultPlatformServices = PlatformServices.Default;

            if (defaultPlatformServices != null)
            {
                if (defaultPlatformServices.Application != null)
                {
                    var appEnv = defaultPlatformServices.Application;
                    if (!string.IsNullOrEmpty(_options.ApplicationBasePath))
                    {
                        appEnv = new WrappedApplicationEnvironment(_options.ApplicationBasePath, appEnv);
                    }

                    services.TryAddSingleton(appEnv);
                }

                if (defaultPlatformServices.Runtime != null)
                {
                    services.TryAddSingleton(defaultPlatformServices.Runtime);
                }
            }

            if (_configureServices != null)
            {
                _configureServices(services);
            }

            return services;
        }
        public async Task ExecuteOperationMiddleware_Mutation_ExecutedSerially()
        {
            // arrange
            var state = 0;

            var schema = Schema.Create(
                FileResource.Open("MutationExecutionSchema.graphql"),
                cnf =>
            {
                cnf.BindResolver(() => state)
                .To("Query", "state");
                cnf.BindResolver(() => state)
                .To("CurrentState", "theNumber");
                cnf.BindResolver(
                    ctx => state = ctx.Argument <int>("newNumber"))
                .To("Mutation", "changeTheNumber");
            });

            DocumentNode query = Parser.Default.Parse(
                FileResource.Open("MutationExecutionQuery.graphql"));

            OperationDefinitionNode operationNode = query.Definitions
                                                    .OfType <OperationDefinitionNode>()
                                                    .FirstOrDefault();

            var operation = new Operation
                            (
                query,
                operationNode,
                new VariableValueBuilder(
                    schema,
                    operationNode)
                .CreateValues(new Dictionary <string, object>()),
                schema.MutationType,
                null
                            );

            IReadOnlyQueryRequest request = new QueryRequest("{ a }");

            var observable = new DiagnosticListener("Foo");

            var services = new DictionaryServiceProvider(
                new KeyValuePair <Type, object>(
                    typeof(IErrorHandler),
                    ErrorHandler.Default),
                new KeyValuePair <Type, object>(
                    typeof(DiagnosticListener),
                    observable),
                new KeyValuePair <Type, object>(
                    typeof(DiagnosticSource),
                    observable));

            var context = new QueryContext
                          (
                schema,
                services.CreateRequestServiceScope(),
                request,
                fs => fs.Field.Middleware
                          )
            {
                Document  = query,
                Operation = operation
            };

            var options          = new QueryExecutionOptions();
            var strategyResolver = new ExecutionStrategyResolver(options);

            var diagnostics = new QueryExecutionDiagnostics(
                new DiagnosticListener("Foo"),
                new IDiagnosticObserver[0],
                TracingPreference.Never);

            var middleware = new ExecuteOperationMiddleware(
                c => Task.CompletedTask,
                strategyResolver,
                new Cache <DirectiveMiddlewareCompiler>(10),
                diagnostics);

            // act
            await middleware.InvokeAsync(context);

            // assert
            Assert.NotNull(context.Result);
            context.Result.Snapshot();
        }
        public void TestShortcutKeywords()
        {
            using (var eventSourceListener = new TestDiagnosticSourceEventListener())
                // These are look-alikes for the real ones.
                using (var aspNetCoreSource = new DiagnosticListener("Microsoft.AspNetCore"))
                    using (var entityFrameworkCoreSource = new DiagnosticListener("Microsoft.EntityFrameworkCore"))
                    {
                        // These are from DiagnosticSourceEventListener.
                        var Messages                    = (EventKeywords)0x1;
                        var Events                      = (EventKeywords)0x2;
                        var AspNetCoreHosting           = (EventKeywords)0x1000;
                        var EntityFrameworkCoreCommands = (EventKeywords)0x2000;

                        // Turn on listener using just the keywords
                        eventSourceListener.Enable(null, Messages | Events | AspNetCoreHosting | EntityFrameworkCoreCommands);

                        Assert.Equal(0, eventSourceListener.EventCount);

                        // Start a ASP.NET Request
                        aspNetCoreSource.Write("Microsoft.AspNetCore.Hosting.BeginRequest",
                                               new
                        {
                            httpContext = new
                            {
                                Request = new
                                {
                                    Method      = "Get",
                                    Host        = "MyHost",
                                    Path        = "MyPath",
                                    QueryString = "MyQuery"
                                }
                            }
                        });
                        // Check that the morphs work as expected.
                        Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                        Assert.Equal("Activity1Start", eventSourceListener.LastEvent.EventSourceEventName);
                        Assert.Equal("Microsoft.AspNetCore", eventSourceListener.LastEvent.SourceName);
                        Assert.Equal("Microsoft.AspNetCore.Hosting.BeginRequest", eventSourceListener.LastEvent.EventName);
                        Assert.True(4 <= eventSourceListener.LastEvent.Arguments.Count);
                        Debug.WriteLine("Arg Keys = " + string.Join(" ", eventSourceListener.LastEvent.Arguments.Keys));
                        Debug.WriteLine("Arg Values = " + string.Join(" ", eventSourceListener.LastEvent.Arguments.Values));
                        Assert.Equal("Get", eventSourceListener.LastEvent.Arguments["Method"]);
                        Assert.Equal("MyHost", eventSourceListener.LastEvent.Arguments["Host"]);
                        Assert.Equal("MyPath", eventSourceListener.LastEvent.Arguments["Path"]);
                        Assert.Equal("MyQuery", eventSourceListener.LastEvent.Arguments["QueryString"]);
                        eventSourceListener.ResetEventCountAndLastEvent();

                        // Start a SQL command
                        entityFrameworkCoreSource.Write("Microsoft.EntityFrameworkCore.BeforeExecuteCommand",
                                                        new
                        {
                            Command = new
                            {
                                Connection = new
                                {
                                    DataSource = "MyDataSource",
                                    Database   = "MyDatabase",
                                },
                                CommandText = "MyCommand"
                            }
                        });
                        Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                        Assert.Equal("Activity2Start", eventSourceListener.LastEvent.EventSourceEventName);
                        Assert.Equal("Microsoft.EntityFrameworkCore", eventSourceListener.LastEvent.SourceName);
                        Assert.Equal("Microsoft.EntityFrameworkCore.BeforeExecuteCommand", eventSourceListener.LastEvent.EventName);
                        Assert.True(3 <= eventSourceListener.LastEvent.Arguments.Count);
                        Assert.Equal("MyDataSource", eventSourceListener.LastEvent.Arguments["DataSource"]);
                        Assert.Equal("MyDatabase", eventSourceListener.LastEvent.Arguments["Database"]);
                        Assert.Equal("MyCommand", eventSourceListener.LastEvent.Arguments["CommandText"]);
                        eventSourceListener.ResetEventCountAndLastEvent();

                        // Stop the SQL command
                        entityFrameworkCoreSource.Write("Microsoft.EntityFrameworkCore.AfterExecuteCommand", null);
                        Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                        Assert.Equal("Activity2Stop", eventSourceListener.LastEvent.EventSourceEventName);
                        Assert.Equal("Microsoft.EntityFrameworkCore", eventSourceListener.LastEvent.SourceName);
                        Assert.Equal("Microsoft.EntityFrameworkCore.AfterExecuteCommand", eventSourceListener.LastEvent.EventName);
                        eventSourceListener.ResetEventCountAndLastEvent();

                        // Stop the ASP.NET reqeust.
                        aspNetCoreSource.Write("Microsoft.AspNetCore.Hosting.EndRequest",
                                               new
                        {
                            httpContext = new
                            {
                                Response = new
                                {
                                    StatusCode = "200"
                                },
                                TraceIdentifier = "MyTraceId"
                            }
                        });
                        Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                        Assert.Equal("Activity1Stop", eventSourceListener.LastEvent.EventSourceEventName);
                        Assert.Equal("Microsoft.AspNetCore", eventSourceListener.LastEvent.SourceName);
                        Assert.Equal("Microsoft.AspNetCore.Hosting.EndRequest", eventSourceListener.LastEvent.EventName);
                        Assert.True(2 <= eventSourceListener.LastEvent.Arguments.Count);
                        Assert.Equal("MyTraceId", eventSourceListener.LastEvent.Arguments["TraceIdentifier"]);
                        Assert.Equal("200", eventSourceListener.LastEvent.Arguments["StatusCode"]);
                        eventSourceListener.ResetEventCountAndLastEvent();
                    }
        }
Exemple #41
0
        private IServiceCollection BuildHostingServices()
        {
            _options = new WebHostOptions(_config);

            var appEnvironment = PlatformServices.Default.Application;
            var contentRootPath = ResolveContentRootPath(_options.ContentRootPath, appEnvironment.ApplicationBasePath);
            var applicationName = _options.ApplicationName ?? appEnvironment.ApplicationName;

            // Initialize the hosting environment
            _hostingEnvironment.Initialize(applicationName, contentRootPath, _options);

            var services = new ServiceCollection();
            services.AddSingleton(_hostingEnvironment);

            if (_loggerFactory == null)
            {
                _loggerFactory = new LoggerFactory();
            }

            foreach (var configureLogging in _configureLoggingDelegates)
            {
                configureLogging(_loggerFactory);
            }

            //The configured ILoggerFactory is added as a singleton here. AddLogging below will not add an additional one.
            services.AddSingleton(_loggerFactory);

            //This is required to add ILogger of T.
            services.AddLogging();

            services.AddTransient<IApplicationBuilderFactory, ApplicationBuilderFactory>();
            services.AddTransient<IHttpContextFactory, HttpContextFactory>();
            services.AddOptions();

            var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
            services.AddSingleton<DiagnosticSource>(diagnosticSource);
            services.AddSingleton<DiagnosticListener>(diagnosticSource);

            // Conjure up a RequestServices
            services.AddTransient<IStartupFilter, AutoRequestServicesStartupFilter>();

            // Ensure object pooling is available everywhere.
            services.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();

            if (!string.IsNullOrEmpty(_options.StartupAssembly))
            {
                try
                {
                    var startupType = StartupLoader.FindStartupType(_options.StartupAssembly, _hostingEnvironment.EnvironmentName);

                    if (typeof(IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo()))
                    {
                        services.AddSingleton(typeof(IStartup), startupType);
                    }
                    else
                    {
                        services.AddSingleton(typeof(IStartup), sp =>
                        {
                            var hostingEnvironment = sp.GetRequiredService<IHostingEnvironment>();
                            var methods = StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName);
                            return new ConventionBasedStartup(methods);
                        });
                    }
                }
                catch (Exception ex)
                {
                    var capture = ExceptionDispatchInfo.Capture(ex);
                    services.AddSingleton<IStartup>(_ =>
                    {
                        capture.Throw();
                        return null;
                    });
                }
            }

            foreach (var configureServices in _configureServicesDelegates)
            {
                configureServices(services);
            }

            return services;
        }
Exemple #42
0
        private IServiceCollection BuildCommonServices(out AggregateException hostingStartupErrors)
        {
            hostingStartupErrors = null;

            _options = new WebHostOptions(_config, Assembly.GetEntryAssembly()?.GetName().Name);

            if (!_options.PreventHostingStartup)
            {
                var exceptions = new List <Exception>();

                // Execute the hosting startup assemblies
                foreach (var assemblyName in _options.GetFinalHostingStartupAssemblies().Distinct(StringComparer.OrdinalIgnoreCase))
                {
                    try
                    {
                        var assembly = Assembly.Load(new AssemblyName(assemblyName));

                        foreach (var attribute in assembly.GetCustomAttributes <HostingStartupAttribute>())
                        {
                            var hostingStartup = (IHostingStartup)Activator.CreateInstance(attribute.HostingStartupType);
                            hostingStartup.Configure(this);
                        }
                    }
                    catch (Exception ex)
                    {
                        // Capture any errors that happen during startup
                        exceptions.Add(new InvalidOperationException($"Startup assembly {assemblyName} failed to execute. See the inner exception for more details.", ex));
                    }
                }

                if (exceptions.Count > 0)
                {
                    hostingStartupErrors = new AggregateException(exceptions);
                }
            }

            var contentRootPath = ResolveContentRootPath(_options.ContentRootPath, AppContext.BaseDirectory);

            // Initialize the hosting environment
            _hostingEnvironment.Initialize(contentRootPath, _options);
            _context.HostingEnvironment = _hostingEnvironment;

            var services = new ServiceCollection();

            services.AddSingleton(_options);
            services.AddSingleton <IHostingEnvironment>(_hostingEnvironment);
            services.AddSingleton <Extensions.Hosting.IHostingEnvironment>(_hostingEnvironment);
            services.AddSingleton(_context);

            var builder = new ConfigurationBuilder()
                          .SetBasePath(_hostingEnvironment.ContentRootPath)
                          .AddConfiguration(_config);

            _configureAppConfigurationBuilder?.Invoke(_context, builder);

            var configuration = builder.Build();

            services.AddSingleton <IConfiguration>(configuration);
            _context.Configuration = configuration;

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

            services.AddSingleton <DiagnosticListener>(listener);
            services.AddSingleton <DiagnosticSource>(listener);

            services.AddTransient <IApplicationBuilderFactory, ApplicationBuilderFactory>();
            services.AddTransient <IHttpContextFactory, HttpContextFactory>();
            services.AddScoped <IMiddlewareFactory, MiddlewareFactory>();
            services.AddOptions();
            services.AddLogging();

            // Conjure up a RequestServices
            services.AddTransient <IStartupFilter, AutoRequestServicesStartupFilter>();
            services.AddTransient <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>();

            // Ensure object pooling is available everywhere.
            services.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();

            if (!string.IsNullOrEmpty(_options.StartupAssembly))
            {
                try
                {
                    var startupType = StartupLoader.FindStartupType(_options.StartupAssembly, _hostingEnvironment.EnvironmentName);

                    if (typeof(IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo()))
                    {
                        services.AddSingleton(typeof(IStartup), startupType);
                    }
                    else
                    {
                        services.AddSingleton(typeof(IStartup), sp =>
                        {
                            var hostingEnvironment = sp.GetRequiredService <IHostingEnvironment>();
                            var methods            = StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName);
                            return(new ConventionBasedStartup(methods));
                        });
                    }
                }
                catch (Exception ex)
                {
                    var capture = ExceptionDispatchInfo.Capture(ex);
                    services.AddSingleton <IStartup>(_ =>
                    {
                        capture.Throw();
                        return(null);
                    });
                }
            }

            _configureServices?.Invoke(_context, services);

            return(services);
        }
        public void TestBadProperties()
        {
            using (var eventSourceListener = new TestDiagnosticSourceEventListener())
            using (var diagnosticSourceListener = new DiagnosticListener("TestBadPropertiesSource"))
            {
                Assert.Equal(0, eventSourceListener.EventCount);

                // This has a syntax error in the Url case, so it should be ignored.  
                eventSourceListener.Enable("TestBadPropertiesSource/TestEvent1:cls.Ur-+l");

                /***************************************************************************************/
                // Emit an event that matches the first pattern. 
                MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
                if (diagnosticSourceListener.IsEnabled("TestEvent1"))
                    diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });

                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("TestBadPropertiesSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
                Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]);
                Assert.Equal("4", eventSourceListener.LastEvent.Arguments["propInt"]);
                eventSourceListener.ResetEventCountAndLastEvent();
            }
        }
 public HostingApplicationDiagnostics(ILogger logger, DiagnosticListener diagnosticListener)
 {
     _logger             = logger;
     _diagnosticListener = diagnosticListener;
 }
        public void TestActivities()
        {
            using (var eventSourceListener = new TestDiagnosticSourceEventListener())
            using (var diagnosticSourceListener = new DiagnosticListener("TestActivitiesSource"))
            {
                Assert.Equal(0, eventSourceListener.EventCount);
                eventSourceListener.Enable(
                    "TestActivitiesSource/TestActivity1Start@Activity1Start\r\n" +
                    "TestActivitiesSource/TestActivity1Stop@Activity1Stop\r\n" +
                    "TestActivitiesSource/TestActivity2Start@Activity2Start\r\n" +
                    "TestActivitiesSource/TestActivity2Stop@Activity2Stop\r\n" +
                    "TestActivitiesSource/TestEvent\r\n"
                    );

                // Start activity 1
                diagnosticSourceListener.Write("TestActivity1Start", new { propStr = "start" });
                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("Activity1Start", eventSourceListener.LastEvent.EventSourceEventName);
                Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestActivity1Start", eventSourceListener.LastEvent.EventName);
                Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("start", eventSourceListener.LastEvent.Arguments["propStr"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                // Start nested activity 2
                diagnosticSourceListener.Write("TestActivity2Start", new { propStr = "start" });
                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("Activity2Start", eventSourceListener.LastEvent.EventSourceEventName);
                Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestActivity2Start", eventSourceListener.LastEvent.EventName);
                Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("start", eventSourceListener.LastEvent.Arguments["propStr"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                // Send a normal event 
                diagnosticSourceListener.Write("TestEvent", new { propStr = "event" });
                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("Event", eventSourceListener.LastEvent.EventSourceEventName);
                Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent", eventSourceListener.LastEvent.EventName);
                Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("event", eventSourceListener.LastEvent.Arguments["propStr"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                // Stop nested activity 2
                diagnosticSourceListener.Write("TestActivity2Stop", new { propStr = "stop" });
                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("Activity2Stop", eventSourceListener.LastEvent.EventSourceEventName);
                Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestActivity2Stop", eventSourceListener.LastEvent.EventName);
                Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("stop", eventSourceListener.LastEvent.Arguments["propStr"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                // Stop activity 1
                diagnosticSourceListener.Write("TestActivity1Stop", new { propStr = "stop" });
                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("Activity1Stop", eventSourceListener.LastEvent.EventSourceEventName);
                Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestActivity1Stop", eventSourceListener.LastEvent.EventName);
                Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("stop", eventSourceListener.LastEvent.Arguments["propStr"]);
                eventSourceListener.ResetEventCountAndLastEvent();
            }
        }
Exemple #46
0
 public abstract bool ShouldSubscribe(DiagnosticListener diagnosticListener);
        /// <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 OnEvent(KeyValuePair <string, object> evnt, DiagnosticListener diagnosticListener)
 {
     this.EventCalls.Add(new Tuple <string, KeyValuePair <string, object> >(diagnosticListener.Name, evnt));
 }
        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;
        }
        public void LinuxNewLineConventions()
        {
            using (var eventSourceListener = new TestDiagnosticSourceEventListener())
            using (var diagnosticSourceListener = new DiagnosticListener("LinuxNewLineConventionsSource"))
            {
                Assert.Equal(0, eventSourceListener.EventCount);

                // Turn on events with both implicit and explicit types You can have whitespace 
                // before and after each spec.   Use \n rather than \r\n 
                eventSourceListener.Enable(
                    "  LinuxNewLineConventionsSource/TestEvent1:-cls_Point_X=cls.Point.X\n" +
                    "  LinuxNewLineConventionsSource/TestEvent2:-cls_Url=cls.Url\n"
                    );

                /***************************************************************************************/
                // Emit an event that matches the first pattern. 
                MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
                if (diagnosticSourceListener.IsEnabled("TestEvent1"))
                    diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });

                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("LinuxNewLineConventionsSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
                Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("3", eventSourceListener.LastEvent.Arguments["cls_Point_X"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                /***************************************************************************************/
                // Emit an event that matches the second pattern. 
                if (diagnosticSourceListener.IsEnabled("TestEvent2"))
                    diagnosticSourceListener.Write("TestEvent2", new { prop2Str = "hello", prop2Int = 8, cls = val });

                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.  
                Assert.Equal("LinuxNewLineConventionsSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName);
                Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("MyUrl", eventSourceListener.LastEvent.Arguments["cls_Url"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                // Emit an event that does not match either pattern.  (thus will be filtered out)
                if (diagnosticSourceListener.IsEnabled("TestEvent3"))
                    diagnosticSourceListener.Write("TestEvent3", new { propStr = "prop3", });
                Assert.Equal(0, eventSourceListener.EventCount);        // No Event should be fired.  
            }

            // Make sure that there are no Diagnostic Listeners left over.  
            DiagnosticListener.AllListeners.Subscribe(DiagnosticSourceTest.MakeObserver(delegate (DiagnosticListener listen)
            {
                Assert.True(!listen.Name.StartsWith("BuildTestSource"));
            }));
        }
        public async Task Start()
        {
            IHttpApplication <HostingApplication.Context> app;

            try
            {
                if (_handler == null)
                {
                    throw new Exception("Missing Handler - Call SetHandler()");
                }

                ILoggerFactory loggerFactory = new LoggerFactory();
                loggerFactory.AddProvider(new KestrelLoggerProvider());
                var services = new ServiceCollection();
                services.AddSingleton(loggerFactory);
                services.AddLogging();

                var serviceProvider      = GetProviderFromFactory(services);
                var kestrelServerOptions = Options.Create(new KestrelServerOptions());
                kestrelServerOptions.Value.ApplicationServices = serviceProvider;

                foreach (uint httpPort in _setting.HttpPorts)
                {
                    kestrelServerOptions.Value.ListenAnyIP((int)httpPort);
                }

                if (_setting.HttpsEnabled)
                {
                    kestrelServerOptions.Value.ListenAnyIP(_setting.HttpsPort,
                                                           listenOptions =>
                    {
                        var cert = new X509Certificate2(_setting.HttpsCertPath,
                                                        _setting.HttpsCertPw);
                        listenOptions.UseHttps(new HttpsConnectionAdapterOptions
                        {
                            ServerCertificate = cert
                                                //  SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls
                        });
                    });
                }
                // kestrelServerOptions.Value.ListenAnyIP(_setting.WebSetting.HttpsPort);

                kestrelServerOptions.Value.AddServerHeader = false;

                var socketTransportOptions = Options.Create(new SocketTransportOptions());
                _applicationLifetime = new ApplicationLifetime(
                    loggerFactory.CreateLogger <ApplicationLifetime>()
                    );
                ITransportFactory transportFactory = new SocketTransportFactory(
                    socketTransportOptions, _applicationLifetime, loggerFactory
                    );


                _server = new KestrelServer(kestrelServerOptions, transportFactory, loggerFactory);
                var diagnosticListener = new DiagnosticListener("a");
                var formOptions        = Options.Create(new FormOptions());
                IHttpContextFactory httpContextFactory = new HttpContextFactory(formOptions);
                app = new HostingApplication(
                    RequestDelegate,
                    loggerFactory.CreateLogger <KestrelWebServer>(),
                    diagnosticListener,
                    httpContextFactory
                    );
            }
            catch (Exception ex)
            {
                Logger.Exception(ex);
                return;
            }

            var   kestrelStartup = _server.StartAsync(app, _cancellationTokenSource.Token);
            await kestrelStartup;

            _cancellationTokenSource.Token.Register(
                state => ((IApplicationLifetime)state).StopApplication(),
                _applicationLifetime
                );
            var completionSource = new TaskCompletionSource <object>(
                TaskCreationOptions.RunContinuationsAsynchronously
                );

            _applicationLifetime.ApplicationStopping.Register(
                obj => ((TaskCompletionSource <object>)obj).TrySetResult(null),
                completionSource
                );
            var   kestrelCompleted       = completionSource.Task;
            var   kestrelCompletedResult = await kestrelCompleted;
            var   kestrelShutdown        = _server.StopAsync(new CancellationToken());
            await kestrelShutdown;
        }
        public void TestWildCardSourceName()
        {
            using (var eventSourceListener = new TestDiagnosticSourceEventListener())
            using (var diagnosticSourceListener1 = new DiagnosticListener("TestWildCardSourceName1"))
            using (var diagnosticSourceListener2 = new DiagnosticListener("TestWildCardSourceName2"))
            {
                eventSourceListener.Filter = (DiagnosticSourceEvent evnt) => evnt.SourceName.StartsWith("TestWildCardSourceName");

                // Turn On Everything.  Note that because of concurrent testing, we may get other sources as well.
                // but we filter them out because we set eventSourceListener.Filter.   
                eventSourceListener.Enable("");

                Assert.True(diagnosticSourceListener1.IsEnabled("TestEvent1"));
                Assert.True(diagnosticSourceListener1.IsEnabled("TestEvent2"));
                Assert.True(diagnosticSourceListener2.IsEnabled("TestEvent1"));
                Assert.True(diagnosticSourceListener2.IsEnabled("TestEvent2"));

                Assert.Equal(0, eventSourceListener.EventCount);

                diagnosticSourceListener1.Write("TestEvent1", new { prop111 = "prop111Val", prop112 = 112 });
                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("TestWildCardSourceName1", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
                Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("prop111Val", eventSourceListener.LastEvent.Arguments["prop111"]);
                Assert.Equal("112", eventSourceListener.LastEvent.Arguments["prop112"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                diagnosticSourceListener1.Write("TestEvent2", new { prop121 = "prop121Val", prop122 = 122 });
                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("TestWildCardSourceName1", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName);
                Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("prop121Val", eventSourceListener.LastEvent.Arguments["prop121"]);
                Assert.Equal("122", eventSourceListener.LastEvent.Arguments["prop122"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                diagnosticSourceListener2.Write("TestEvent1", new { prop211 = "prop211Val", prop212 = 212 });
                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("TestWildCardSourceName2", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
                Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("prop211Val", eventSourceListener.LastEvent.Arguments["prop211"]);
                Assert.Equal("212", eventSourceListener.LastEvent.Arguments["prop212"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                diagnosticSourceListener2.Write("TestEvent2", new { prop221 = "prop221Val", prop222 = 122 });
                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("TestWildCardSourceName2", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName);
                Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("prop221Val", eventSourceListener.LastEvent.Arguments["prop221"]);
                Assert.Equal("122", eventSourceListener.LastEvent.Arguments["prop222"]);
                eventSourceListener.ResetEventCountAndLastEvent();
            }
        }
 public ActivityRequestTracer(ILoggerFactory loggerFactory, ClusterOptions options)
 {
     _loggerFactory      = loggerFactory;
     _diagnosticListener = new DiagnosticListener(RequestTracing.SourceName);
     _diagnosticListener.Subscribe(new ThresholdActivityObserver(loggerFactory, options.ThresholdOptions ?? new ThresholdOptions()));
 }
        public void TestWildCardEventName()
        {
            using (var eventSourceListener = new TestDiagnosticSourceEventListener())
            using (var diagnosticSourceListener = new DiagnosticListener("TestWildCardEventNameSource"))
            {
                Assert.Equal(0, eventSourceListener.EventCount);

                // Turn on events with both implicit and explicit types 
                eventSourceListener.Enable("TestWildCardEventNameSource");

                /***************************************************************************************/
                // Emit an event, check that all implicit properties are generated
                MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
                if (diagnosticSourceListener.IsEnabled("TestEvent1"))
                    diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });

                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("TestWildCardEventNameSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
                Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]);
                Assert.Equal("4", eventSourceListener.LastEvent.Arguments["propInt"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                /***************************************************************************************/
                // Emit the same event, with a different set of implicit properties 
                if (diagnosticSourceListener.IsEnabled("TestEvent1"))
                    diagnosticSourceListener.Write("TestEvent1", new { propStr2 = "hi2", cls = val });

                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("TestWildCardEventNameSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
                Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("hi2", eventSourceListener.LastEvent.Arguments["propStr2"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                /***************************************************************************************/
                // Emit an event from another diagnostic source with the same event name.  
                // It will be filtered out.  
                using (var diagnosticSourceListener2 = new DiagnosticListener("TestWildCardEventNameSource2"))
                {
                    if (diagnosticSourceListener2.IsEnabled("TestEvent1"))
                        diagnosticSourceListener2.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });
                }
                Assert.Equal(0, eventSourceListener.EventCount);        // No Event should be fired.  
            }
        }
Exemple #55
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();
                }
        }
        public void TestSpecificEvents()
        {
            using (var eventSourceListener = new TestDiagnosticSourceEventListener())
            using (var diagnosticSourceListener = new DiagnosticListener("TestSpecificEventsSource"))
            {
                Assert.Equal(0, eventSourceListener.EventCount);

                // Turn on events with both implicit and explicit types You can have whitespace 
                // before and after each spec.  
                eventSourceListener.Enable(
                    "  TestSpecificEventsSource/TestEvent1:cls_Point_X=cls.Point.X;cls_Point_Y=cls.Point.Y\r\n" +
                    "  TestSpecificEventsSource/TestEvent2:cls_Url=cls.Url\r\n"
                    );

                /***************************************************************************************/
                // Emit an event that matches the first pattern. 
                MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
                if (diagnosticSourceListener.IsEnabled("TestEvent1"))
                    diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });

                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("TestSpecificEventsSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
                Assert.Equal(4, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]);
                Assert.Equal("4", eventSourceListener.LastEvent.Arguments["propInt"]);
                Assert.Equal("3", eventSourceListener.LastEvent.Arguments["cls_Point_X"]);
                Assert.Equal("5", eventSourceListener.LastEvent.Arguments["cls_Point_Y"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                /***************************************************************************************/
                // Emit an event that matches the second pattern. 
                if (diagnosticSourceListener.IsEnabled("TestEvent2"))
                    diagnosticSourceListener.Write("TestEvent2", new { prop2Str = "hello", prop2Int = 8, cls = val });

                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.  
                Assert.Equal("TestSpecificEventsSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName);
                Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("hello", eventSourceListener.LastEvent.Arguments["prop2Str"]);
                Assert.Equal("8", eventSourceListener.LastEvent.Arguments["prop2Int"]);
                Assert.Equal("MyUrl", eventSourceListener.LastEvent.Arguments["cls_Url"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                // Emit an event that does not match either pattern.  (thus will be filtered out)
                if (diagnosticSourceListener.IsEnabled("TestEvent3"))
                    diagnosticSourceListener.Write("TestEvent3", new { propStr = "prop3", });
                Assert.Equal(0, eventSourceListener.EventCount);        // No Event should be fired.  

                /***************************************************************************************/
                // Emit an event from another diagnostic source with the same event name.  
                // It will be filtered out.  
                using (var diagnosticSourceListener2 = new DiagnosticListener("TestSpecificEventsSource2"))
                {
                    if (diagnosticSourceListener2.IsEnabled("TestEvent1"))
                        diagnosticSourceListener2.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });
                }
                Assert.Equal(0, eventSourceListener.EventCount);        // No Event should be fired.  

                // Disable all the listener and insure that no more events come through.  
                eventSourceListener.Disable();

                diagnosticSourceListener.Write("TestEvent1", null);
                diagnosticSourceListener.Write("TestEvent2", null);

                Assert.Equal(0, eventSourceListener.EventCount);        // No Event should be received.  
            }

            // Make sure that there are no Diagnostic Listeners left over.  
            DiagnosticListener.AllListeners.Subscribe(DiagnosticSourceTest.MakeObserver(delegate (DiagnosticListener listen)
            {
                Assert.True(!listen.Name.StartsWith("BuildTestSource"));
            }));
        }
 private void AssertEnabledFor(DiagnosticListener listener, string eventName) =>
 Assert.IsTrue(listener.IsEnabled(eventName), "Should be enabled for '{0}'", eventName);
        public void TestNulls()
        {
            using (var eventSourceListener = new TestDiagnosticSourceEventListener())
            using (var diagnosticSourceListener = new DiagnosticListener("TestNullsTestSource"))
            {
                Assert.Equal(0, eventSourceListener.EventCount);

                // Turn on events with both implicit and explicit types 
                eventSourceListener.Enable("TestNullsTestSource/TestEvent1:cls.Url;cls_Point_X=cls.Point.X");

                /***************************************************************************************/
                // Emit a null arguments object. 

                if (diagnosticSourceListener.IsEnabled("TestEvent1"))
                    diagnosticSourceListener.Write("TestEvent1", null);

                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
                Assert.Equal(0, eventSourceListener.LastEvent.Arguments.Count);
                eventSourceListener.ResetEventCountAndLastEvent();

                /***************************************************************************************/
                // Emit an arguments object with nulls in it.   

                MyClass val = null;
                string strVal = null;
                if (diagnosticSourceListener.IsEnabled("TestEvent1"))
                    diagnosticSourceListener.Write("TestEvent1", new { cls = val, propStr = "propVal1", propStrNull = strVal });

                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
                Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]);
                Assert.Equal("", eventSourceListener.LastEvent.Arguments["propStrNull"]);   // null strings get turned into empty strings
                eventSourceListener.ResetEventCountAndLastEvent();

                /***************************************************************************************/
                // Emit an arguments object that points at null things

                MyClass val1 = new MyClass() { Url = "myUrlVal", Point = null };
                if (diagnosticSourceListener.IsEnabled("TestEvent1"))
                    diagnosticSourceListener.Write("TestEvent1", new { cls = val1, propStr = "propVal1" });

                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
                Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]);
                Assert.Equal("myUrlVal", eventSourceListener.LastEvent.Arguments["Url"]);
                eventSourceListener.ResetEventCountAndLastEvent();

                /***************************************************************************************/
                // Emit an arguments object that points at null things (variation 2)

                MyClass val2 = new MyClass() { Url = null, Point = new MyPoint() { X = 8, Y = 9 } };
                if (diagnosticSourceListener.IsEnabled("TestEvent1"))
                    diagnosticSourceListener.Write("TestEvent1", new { cls = val2, propStr = "propVal1" });

                Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
                Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName);
                Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
                Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
                Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]);
                Assert.Equal("8", eventSourceListener.LastEvent.Arguments["cls_Point_X"]);
                eventSourceListener.ResetEventCountAndLastEvent();
            }
        }
Exemple #59
0
 public FakeSqlClientDiagnosticSource()
 {
     this.listener = new DiagnosticListener(SqlClientInstrumentation.SqlClientDiagnosticListenerName);
 }
        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;
        }