private static void InitProfilerSettings() { MiniProfilerOptions options = new MiniProfilerOptions() { Storage = new MemoryCacheStorage(new TimeSpan(1, 0, 0)), PopupRenderPosition = RenderPosition.Right, // defaults to left PopupMaxTracesToShow = 10, // defaults to 15 // ResultsAuthorize (optional - open to all by default): // because profiler results can contain sensitive data (e.g. sql queries with parameter values displayed), we // can define a function that will authorize clients to see the JSON or full page results. // we use it on http://stackoverflow.com to check that the request cookies belong to a valid developer. ResultsAuthorize = request => request.IsLocal, // the list of all sessions in the store is restricted by default, you must return true to allow it ResultsListAuthorize = request => request.IsLocal, // Stack trace settings StackMaxLength = 256, // default is 120 characters, } .AddViewProfiling(); // Add MVC view profiling options.IgnoredPaths.Add("/hangfire"); MiniProfiler.Configure(options); MiniProfilerEF6.Initialize(); }
public TestMemoryCacheStorage() { Options = new MiniProfilerOptions() { Storage = new MemoryCacheStorage(new TimeSpan(1, 0, 0)) }; }
protected AspNetCoreTest(ITestOutputHelper output) : base(output) { // Instance per class, so multiple tests swapping the provider don't cause issues here // It's not a threading issue of the profiler, but rather tests swapping providers Options = new MiniProfilerOptions() { StopwatchProvider = () => new UnitTestStopwatch(), Storage = new MemoryCacheStorage(GetMemoryCache(), TimeSpan.FromDays(1)) }; }
protected AspNetTest(ITestOutputHelper output) : base(output) { ThreadPool.SetMinThreads(50, 50); // Instance per class, so multiple tests swapping the provider don't cause issues here // It's not a threading issue of the profiler, but rather tests swapping providers MiniProfiler.Configure(Options = new MiniProfilerOptions() { StopwatchProvider = () => new UnitTestStopwatch(), Storage = new MemoryCacheStorage(TimeSpan.FromDays(1)) }); }
/// <summary> /// Adds view profiling to MiniProfiler, so that view times show up in profilers. /// </summary> /// <param name="options">The options object to configure, only used for chaining.</param> public static MiniProfilerOptions AddViewProfiling(this MiniProfilerOptions options) { var copy = ViewEngines.Engines.ToList(); ViewEngines.Engines.Clear(); foreach (var item in copy) { ViewEngines.Engines.Add(new ProfilingViewEngine(item)); } return(options); }
// Reset for each inheritor protected BaseTest() { // Instance per class, so multiple tests swapping the provider don't cause issues here // It's not a threading issue of the profiler, but rather tests swapping providers Options = new MiniProfilerOptions() { StopwatchProvider = () => new UnitTestStopwatch(), Storage = new MemoryCacheStorage(TimeSpan.FromDays(1)) }; // To reset the static specifically, can probably remove this... //Options.SetProvider(new DefaultProfilerProvider()); }
protected IWebHostBuilder BasicBuilder(RequestDelegate requestDelegate, [CallerMemberName] string name = null) => new WebHostBuilder() .ConfigureServices(services => services.AddMiniProfiler(o => { o.Storage = new MemoryCacheStorage(GetMemoryCache(), TimeSpan.FromDays(1)); o.StopwatchProvider = () => new UnitTestStopwatch(); o.UserIdProvider = _ => name; CurrentOptions = o; })) .Configure(app => { app.UseMiniProfiler(); app.Run(requestDelegate); });
/// <summary> /// Adds middleware for profiling HTTP requests. /// </summary> /// <param name="builder">The <see cref="IApplicationBuilder"/> instance this method extends.</param> /// <param name="configureOptions">Action to configure options for MiniProfiler.</param> /// <exception cref="ArgumentNullException"><paramref name="builder"/> or <paramref name="configureOptions"/> is <c>null</c>.</exception> public static IApplicationBuilder UseMiniProfiler(this IApplicationBuilder builder, Action <MiniProfilerOptions> configureOptions) { _ = builder ?? throw new ArgumentNullException(nameof(builder)); _ = configureOptions ?? throw new ArgumentNullException(nameof(configureOptions)); // Register all IMiniProfilerDiagnosticListeners that were registered, e.g. EntityFramework var listeners = builder.ApplicationServices.GetServices <IMiniProfilerDiagnosticListener>(); var initializer = new DiagnosticInitializer(listeners); initializer.Start(); var options = new MiniProfilerOptions(); configureOptions(options); return(builder.UseMiddleware <MiniProfilerMiddleware>(options)); }
public WebProfiler() { // create our own provider, which can provide a profiler even during boot _provider = new WebProfilerProvider(); //see https://miniprofiler.com/dotnet/AspDotNet var options = new MiniProfilerOptions { SqlFormatter = new SqlServerFormatter(), StackMaxLength = 5000, ProfilerProvider = _provider }; // this is a default path and by default it performs a 'contains' check which will match our content controller // (and probably other requests) and ignore them. options.IgnoredPaths.Remove("/content/"); MiniProfiler.Configure(options); }
private void InitProfilerSettings() { MiniProfilerOptions MiniProfilerOptions = new MiniProfilerOptions { Storage = new MultiStorageProvider(new MemoryCacheStorage(new TimeSpan(1, 0, 0))), PopupRenderPosition = RenderPosition.Left, // defaults to left PopupMaxTracesToShow = 10, // defaults to 15 ResultsAuthorize = request => { if ("/home/resultsauthorization".Equals(request.Url.LocalPath, StringComparison.OrdinalIgnoreCase)) { return((request.Url.Query).IndexOf("isauthorized", StringComparison.OrdinalIgnoreCase) >= 0); } return(!DisableProfilingResults); }, ResultsListAuthorize = request => { return(true); }, StackMaxLength = 256, TrackConnectionOpenClose = true } .ExcludeType("SessionFactory") .ExcludeAssembly("NHibernate") .ExcludeMethod("Flush"); MiniProfilerOptions.IgnorePath("/__browserLink"); //Ignore browserLink MiniProfilerOptions.ShowControls = true; // "m" and "c" are displayed on the prompt bar MiniProfiler.Configure(MiniProfilerOptions); MiniProfilerEF.Initialize(); }
/// <summary> /// Customize aspects of the MiniProfiler. /// </summary> private void InitProfilerSettings() { // A powerful feature of the MiniProfiler is the ability to share links to results with other developers. // by default, however, long-term result caching is done in HttpRuntime.Cache, which is very volatile. // // Let's rig up serialization of our profiler results to a database, so they survive app restarts. var options = ProfilerOptions = new MiniProfilerOptions { // Sets up the WebRequestProfilerProvider with // ~/profiler as the route path to use (e.g. /profiler/mini-profiler-includes.js) RouteBasePath = "~/profiler", // Setting up a MultiStorage provider. This will store results in the MemoryCacheStorage (normally the default) and in SqlLite as well. Storage = new MultiStorageProvider( new MemoryCacheStorage(new TimeSpan(1, 0, 0)), // The RecreateDatabase call is only done for testing purposes, so we don't check in the db to source control. new SqliteMiniProfilerStorage(ConnectionString).RecreateDatabase("create table RouteHits(RouteName,HitCount,unique(RouteName))") ), // Different RDBMS have different ways of declaring sql parameters - SQLite can understand inline sql parameters just fine. // By default, sql parameters will be displayed. //SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter(), // These settings are optional and all have defaults, any matching setting specified in .RenderIncludes() will // override the application-wide defaults specified here, for example if you had both: // PopupRenderPosition = RenderPosition.Right; // and in the page: // @MiniProfiler.RenderIncludes(position: RenderPosition.Left) // ...then the position would be on the left that that page, and on the right (the app default) for anywhere that doesn't // specified position in the .RenderIncludes() call. PopupRenderPosition = RenderPosition.Right, // defaults to left PopupMaxTracesToShow = 10, // defaults to 15 // ResultsAuthorize (optional - open to all by default): // because profiler results can contain sensitive data (e.g. sql queries with parameter values displayed), we // can define a function that will authorize clients to see the json or full page results. // we use it on http://stackoverflow.com to check that the request cookies belong to a valid developer. ResultsAuthorize = request => { // you may implement this if you need to restrict visibility of profiling on a per request basis // for example, for this specific path, we'll only allow profiling if a query parameter is set if ("/Home/ResultsAuthorization".Equals(request.Url.LocalPath, StringComparison.OrdinalIgnoreCase)) { return((request.Url.Query).ToLower().Contains("isauthorized")); } // all other paths can check our global switch return(!DisableProfilingResults); }, // ResultsListAuthorize (optional - open to all by default) // the list of all sessions in the store is restricted by default, you must return true to allow it ResultsListAuthorize = request => { // you may implement this if you need to restrict visibility of profiling lists on a per request basis return(true); // all requests are legit in our happy world }, // Stack trace settings StackMaxLength = 256, // default is 120 characters } // Optional settings to control the stack trace output in the details pane .ExcludeType("SessionFactory") // Ignore any class with the name of SessionFactory) .ExcludeAssembly("NHibernate") // Ignore any assembly named NHibernate .ExcludeMethod("Flush"); // Ignore any method with the name of Flush MiniProfilerHandler.Configure(options); MiniProfilerEF6.Initialize(); }
/// <summary> /// Call this from Application_Start in your Global.asax.cs file. Besides this call, there should be no other code in the method. /// </summary> /// <param name="globalInitializer">The system's global initializer. Do not pass null.</param> /// <param name="appInitializer">The application initializer, which performs web-site specific initialization and cleanup. If you have one of these you /// should name the class AppInitializer.</param> public static void InitStatics(SystemInitializer globalInitializer, SystemInitializer appInitializer = null) { // This is a hack to support data-access state in WCF services. var wcfDataAccessState = new ThreadLocal <DataAccessState>(() => new DataAccessState()); // Initialize system. var initTimeDataAccessState = new ThreadLocal <DataAccessState>(() => new DataAccessState()); try { GlobalInitializationOps.InitStatics( globalInitializer, Path.GetFileName(Path.GetDirectoryName(HttpRuntime.AppDomainAppPath)), false, mainDataAccessStateGetter: () => { return(EwfApp.Instance != null ? EwfApp.Instance.RequestState != null ? EwfApp.Instance.RequestState.DataAccessState : initTimeDataAccessState.Value : System.ServiceModel.OperationContext.Current != null ? wcfDataAccessState.Value : null); }); } catch { // Suppress all exceptions since there is no way to report them. return; } ewlInitialized = true; // Initialize web application. if (!GlobalInitializationOps.SecondaryInitFailed) { EwfApp.ExecuteWithBasicExceptionHandling( () => { EwfConfigurationStatics.Init(); GlobalConfiguration.Configure(WebApiStatics.ConfigureWebApi); var miniProfilerOptions = new MiniProfilerOptions(); miniProfilerOptions.IgnoredPaths.Clear(); MiniProfiler.Configure(miniProfilerOptions); var globalType = BuildManager.GetGlobalAsaxType().BaseType; var providerGetter = new SystemProviderGetter( globalType.Assembly, globalType.Namespace + ".Providers", providerName => @"{0} provider not found in application. To implement, create a class named {0} in ""Your Web Site\Providers"" that derives from App{0}Provider." .FormatWith(providerName)); if (ExternalFunctionalityStatics.SamlFunctionalityEnabled) { ExternalFunctionalityStatics.ExternalSamlProvider.InitAppStatics( providerGetter, () => AuthenticationStatics.SamlIdentityProviders.Select( identityProvider => { using (var client = new HttpClient()) { client.Timeout = new TimeSpan(0, 0, 10); var metadata = Task.Run( async() => { using (var response = await client.GetAsync(identityProvider.MetadataUrl, HttpCompletionOption.ResponseHeadersRead)) { response.EnsureSuccessStatusCode(); var document = new XmlDocument(); using (var stream = await response.Content.ReadAsStreamAsync()) using (var reader = XmlReader.Create(stream)) document.Load(reader); return(document.DocumentElement); } }) .Result; return(metadata, identityProvider.EntityId); } }) .Materialize()); } UrlHandlingStatics.Init( (baseUrlString, appRelativeUrl) => AppRequestState.ExecuteWithUrlHandlerStateDisabled(() => UrlHandlingStatics.ResolveUrl(baseUrlString, appRelativeUrl)?.Last())); CssPreprocessingStatics.Init(globalInitializer.GetType().Assembly, globalType.Assembly); ResourceBase.Init( (requestTransferred, resource) => { if (requestTransferred) { var urlHandlers = new List <BasicUrlHandler>(); UrlHandler urlHandler = resource; do { urlHandlers.Add(urlHandler); }while((urlHandler = urlHandler.GetParent()) != null); AppRequestState.Instance.SetUrlHandlers(urlHandlers); AppRequestState.Instance.SetNewUrlParameterValuesEffective(false); AppRequestState.Instance.SetResource(resource); } else { AppRequestState.Instance.SetResource(resource); } }, () => AppRequestState.Instance.Resource); PageBase.Init( (() => BasePageStatics.AppProvider.GetPageViewDataModificationMethod(), () => BasePageStatics.AppProvider.JavaScriptDocumentReadyFunctionCall), BasicPageContent.GetContent); HyperlinkBehaviorExtensionCreators.Init(ModalBox.GetBrowsingModalBoxOpenStatements); FileUpload.Init(() => ((BasicPageContent)PageBase.Current.BasicContent).FormUsesMultipartEncoding = true); ModalBox.Init(() => ((BasicPageContent)PageBase.Current.BasicContent).BrowsingModalBoxId); CreditCardCollector.Init(() => ((BasicPageContent)PageBase.Current.BasicContent).IncludesStripeCheckout = true); BasePageStatics.Init(providerGetter.GetProvider <AppStandardPageLogicProvider>("StandardPageLogic")); BasicPageContent.Init( contentObjects => { var contentUsesUi = contentObjects.Any(i => i is UiPageContent); var cssInfos = new List <ResourceInfo>(); cssInfos.Add( new ExternalResource( "//fonts.googleapis.com/css2?family=Libre+Franklin:wght@500;600;700&family=Open+Sans:ital,wght@0,400;0,600;0,700;1,400&display=fallback")); cssInfos.Add(new ExternalResource("//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css")); cssInfos.Add(new StaticFiles.Versioned.Third_party.Jquery_ui.Jquery_ui_1114custom_v2.Jquery_uiminCss()); cssInfos.Add(new StaticFiles.Third_party.Select_cssCss()); cssInfos.Add(new StaticFiles.Versioned.Third_party.Chosen.Chosen_v187.ChosenminCss()); cssInfos.Add(new StaticFiles.Third_party.Time_picker.StylesCss()); cssInfos.Add(new ExternalResource("//cdn.jsdelivr.net/qtip2/2.2.1/jquery.qtip.min.css")); cssInfos.Add(new ExternalResource("//cdnjs.cloudflare.com/ajax/libs/dialog-polyfill/0.4.9/dialog-polyfill.min.css")); cssInfos.Add(new StaticFiles.Styles.BasicCss()); if (contentUsesUi) { cssInfos.AddRange( new ResourceInfo[] { new StaticFiles.Styles.Ui.ColorsCss(), new StaticFiles.Styles.Ui.FontsCss(), new StaticFiles.Styles.Ui.LayoutCss(), new StaticFiles.Styles.Ui.TransitionsCss() }); } foreach (var resource in BasePageStatics.AppProvider.GetStyleSheets()) { assertResourceIsIntermediateInstallationPublicResourceWhenNecessary(resource); cssInfos.Add(resource); } if (contentUsesUi) { foreach (var resource in EwfUiStatics.AppProvider.GetStyleSheets()) { assertResourceIsIntermediateInstallationPublicResourceWhenNecessary(resource); cssInfos.Add(resource); } } else { foreach (var resource in BasePageStatics.AppProvider.GetCustomUiStyleSheets()) { assertResourceIsIntermediateInstallationPublicResourceWhenNecessary(resource); cssInfos.Add(resource); } } return(cssInfos); }, (markup, includeStripeCheckout) => { string getElement(ResourceInfo resource) => "<script src=\"{0}\" defer></script>".FormatWith(resource.GetUrl()); var infos = new List <ResourceInfo>(); infos.Add(new ExternalResource("//code.jquery.com/jquery-1.12.3.min.js")); infos.Add(new StaticFiles.Versioned.Third_party.Jquery_ui.Jquery_ui_1114custom_v2.Jquery_uiminJs()); infos.Add(new StaticFiles.Versioned.Third_party.Chosen.Chosen_v187.ChosenjqueryminJs()); infos.Add(new StaticFiles.Third_party.Time_picker.CodeJs()); infos.Add(new ExternalResource("//cdn.jsdelivr.net/qtip2/2.2.1/jquery.qtip.min.js")); infos.Add(new ExternalResource("//cdnjs.cloudflare.com/ajax/libs/dialog-polyfill/0.4.9/dialog-polyfill.min.js")); infos.Add(new StaticFiles.Third_party.Spin_js.SpinminJs()); infos.Add(new ExternalResource("//cdn.ckeditor.com/4.5.8/full/ckeditor.js")); infos.Add(new ExternalResource("https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js")); infos.Add(new ExternalResource("https://instant.page/5.1.0")); if (includeStripeCheckout) { infos.Add(new ExternalResource("https://checkout.stripe.com/checkout.js")); } infos.Add(new StaticFiles.CodeJs()); foreach (var i in infos.Select(getElement)) { markup.Append(i); } markup.Append(MiniProfiler.Current.RenderIncludes().ToHtmlString()); foreach (var resource in BasePageStatics.AppProvider.GetJavaScriptFiles()) { assertResourceIsIntermediateInstallationPublicResourceWhenNecessary(resource); markup.Append(getElement(resource)); } }, () => { var icons = new List <(ResourceInfo, string, string)>(); var faviconPng48X48 = BasePageStatics.AppProvider.FaviconPng48X48; if (faviconPng48X48 != null) { assertResourceIsIntermediateInstallationPublicResourceWhenNecessary(faviconPng48X48); icons.Add((faviconPng48X48, "icon", "48x48")); } var favicon = BasePageStatics.AppProvider.Favicon; if (favicon != null) { assertResourceIsIntermediateInstallationPublicResourceWhenNecessary(favicon); icons.Add((favicon, "icon", "")); } return(icons); }, hideWarnings => { var url = AppRequestState.Instance.Url; if (AppRequestState.Instance.UserAccessible && AppRequestState.Instance.ImpersonatorExists) { url = new UserManagement.Pages.Impersonate( url, optionalParameterSetter: (specifier, parameters) => specifier.User = AppTools.User != null ? AppTools.User.Email : UserManagement.Pages.Impersonate.AnonymousUser).GetUrl(); } return(new NonLiveLogIn( url, optionalParameterSetter: (specifier, parameters) => { specifier.Password = ConfigurationStatics.SystemGeneralProvider.IntermediateLogInPassword; specifier.HideWarnings = hideWarnings; }).GetUrl()); }, () => { if (!AppRequestState.Instance.UserAccessible || !AppRequestState.Instance.ImpersonatorExists || (ConfigurationStatics.IsIntermediateInstallation && !AppRequestState.Instance.IntermediateUserExists)) { return(null); } return("User impersonation is in effect.", new HyperlinkSetup(new UserManagement.Pages.Impersonate(AppRequestState.Instance.Url), "Change user").Append <ActionComponentSetup>( new ButtonSetup( "End impersonation", behavior: new PostBackBehavior( postBack: PostBack.CreateFull( id: "ewfEndImpersonation", modificationMethod: UserImpersonationStatics.EndImpersonation, actionGetter: () => new PostBackAction( new ExternalResource( EwfConfigurationStatics.AppConfiguration.DefaultBaseUrl.GetUrlString( EwfConfigurationStatics.AppSupportsSecureConnections))))))) .Materialize()); }); EwfUiStatics.Init(providerGetter.GetProvider <AppEwfUiProvider>("EwfUi")); AuthenticationStatics.Init( providerGetter.GetProvider <AppAuthenticationProvider>("Authentication"), (user, code) => new UserManagement.Pages.LogIn( "", optionalParameterSetter: (specifier, parameters) => { specifier.User = user; specifier.Code = code; }).GetUrl(), destinationUrl => new UserManagement.Pages.ChangePassword(destinationUrl).GetUrl(disableAuthorizationCheck: true)); Admin.EntitySetup.Init(() => RequestDispatchingStatics.AppProvider.GetFrameworkUrlParent()); RequestDispatchingStatics.Init(providerGetter.GetProvider <AppRequestDispatchingProvider>("RequestDispatching")); EwfInitializationOps.appInitializer = appInitializer; appInitializer?.InitStatics(); executeWithAutomaticDatabaseConnections(AuthenticationStatics.InitAppSpecificLogicDependencies); if (AuthenticationStatics.SamlIdentityProviders.Any() || ExternalFunctionalityStatics.SamlFunctionalityEnabled) { executeWithAutomaticDatabaseConnections(ExternalFunctionalityStatics.ExternalSamlProvider.InitAppSpecificLogicDependencies); } initTimeDataAccessState = null; EwfApp.FrameworkInitialized = true; },
/// <summary> /// Adds middleware for profiling HTTP requests. /// </summary> /// <param name="builder">The <see cref="IApplicationBuilder"/> instance this method extends.</param> /// <param name="options">Options for MiniProfiler.</param> /// <exception cref="ArgumentNullException"><paramref name="builder"/> or <paramref name="options"/> is <c>null</c>.</exception> public static IApplicationBuilder UseMiniProfiler(this IApplicationBuilder builder, MiniProfilerOptions options) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } return(builder.UseMiddleware <MiniProfilerMiddleware>(options)); }
/// <summary> /// Adds middleware for profiling HTTP requests. /// </summary> /// <param name="builder">The <see cref="IApplicationBuilder"/> instance this method extends.</param> /// <param name="options">Options for MiniProfiler.</param> /// <exception cref="ArgumentNullException"><paramref name="builder"/> or <paramref name="options"/> is <c>null</c>.</exception> public static IApplicationBuilder UseMiniProfiler(this IApplicationBuilder builder, MiniProfilerOptions options) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } // Register all IMiniProfilerDiagnosticListeners that were registered, e.g. EntityFramework var listeners = builder.ApplicationServices.GetServices <IMiniProfilerDiagnosticListener>(); var initializer = new DiagnosticInitializer(listeners); initializer.Start(); return(builder.UseMiddleware <MiniProfilerMiddleware>(options)); }