private static void InitializeContainer() { _builder.RegisterControllers(typeof(MvcApplication).Assembly).InstancePerRequest(); IConfigurationBuilder config = new ConfigurationBuilder(); ConfigurationModule module = new ConfigurationModule(config.Build()); ArchBootstrapperAutoFac.Register(_builder); _builder.RegisterModule(module); _builder.RegisterFilterProvider(); IContainer container = _builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); MiniProfiler.Configure(new MiniProfilerOptions() { RouteBasePath = "~/miniprofiler", PopupRenderPosition = RenderPosition.BottomLeft }) .AddViewProfiling() .AddEntityFramework(); }
protected void Application_Start() { OnStart(); MiniProfiler.Configure(new MiniProfilerOptions { // Sets up the route to use for MiniProfiler resources: // Here, ~/profiler is used for things like /profiler/mini-profiler-includes.js RouteBasePath = "~/profiler", // Example of using SQLite storage instead Storage = new MemoryCacheStorage(TimeSpan.FromMinutes(10)), // 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.Current.RenderIncludes(position: RenderPosition.Left) // ...then the position would be on the left on that page, and on the right (the application 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 => request.IsLocal, // 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 this example }, // Stack trace settings StackMaxLength = 256, // default is 120 characters // (Optional) You can disable "Connection Open()", "Connection Close()" (and async variant) tracking. // (defaults to true, and connection opening/closing is tracked) TrackConnectionOpenClose = true } // Optional settings to control the stack trace output in the details pane, examples: .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 .AddViewPofiling() // Add MVC view profiling (you want this) // If using EntityFrameworkCore, here's where it'd go. // .AddEntityFramework() // Extension method in the MiniProfiler.EntityFrameworkCore package ); // If we're using EntityFramework 6, here's where it'd go. // This is in the MiniProfiler.EF6 NuGet package. // MiniProfilerEF6.Initialize(); }
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(); }
protected BaseTest(ITestOutputHelper output) { Output = output; Options = MiniProfiler.Configure(new MiniProfilerTestOptions() { StopwatchProvider = () => new UnitTestStopwatch() }); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); MiniProfiler.Configure(new MiniProfilerOptions()); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); MiniProfiler.Configure(new MiniProfilerOptions().AddViewProfiling()); //MiniProfiler默认设置 MiniProfilerEF6.Initialize(); //配置EF分析 }
public static void RegisterMiniProfiler() { MiniProfiler.Configure(new MiniProfilerOptions() { PopupShowTrivial = true, PopupShowTimeWithChildren = true }).AddViewPofiling(); MiniProfilerEF6.Initialize(); }
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)) }); }
private static void InitializeContainer() { ArchBootstrapper.Register(_container); MiniProfiler.Configure(new MiniProfilerOptions() { RouteBasePath = "~/miniprofiler", PopupRenderPosition = RenderPosition.BottomLeft }) .AddViewProfiling() .AddEntityFramework(); }
public WebProfiler() { // create our own provider, which can provide a profiler even during boot _provider = new WebProfilerProvider(); //see https://miniprofiler.com/dotnet/AspDotNet MiniProfiler.Configure(new MiniProfilerOptions { SqlFormatter = new SqlServerFormatter(), StackMaxLength = 5000, ProfilerProvider = _provider }); }
/// <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. MiniProfiler.Configure(new MiniProfilerOptions { RouteBasePath = "~/profiler" } .AddViewPofiling() // Add MVC view profiling .AddEntityFramework() // Add EF Core ); }
protected void Application_Start() { RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); RegisterBundles(BundleTable.Bundles); // InitProfilerSettings MiniProfiler.Configure(new MiniProfilerOptions { RouteBasePath = "~/profiler" } .AddViewPofiling() // Add MVC view profiling .AddEntityFramework() // Add EF Core ); }
public void Start() { if (_enabled == false) { return; } // See https://miniprofiler.com/dotnet/AspDotNet MiniProfiler.Configure(new MiniProfilerOptions { SqlFormatter = new SqlServerFormatter(), StackMaxLength = 5000 }); MiniProfiler.StartNew(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); MiniProfiler.Configure(new MiniProfilerOptions { RouteBasePath = "~/profiler", PopupRenderPosition = RenderPosition.Right, Storage = new MultiStorageProvider( new MemoryCacheStorage(new TimeSpan(1, 0, 0))) }).AddViewProfiling(); MiniProfilerEF6.Initialize(); }
/// <summary> /// Adds MiniProfiler timings for actions and views. /// </summary> /// <param name="services">The services collection to configure.</param> /// <param name="configureOptions">An Action{MiniProfilerOptions} to configure options for MiniProfiler.</param> public static IMiniProfilerBuilder AddMiniProfiler(this IServiceCollection services, Action <MiniProfilerOptions> configureOptions = null) { services.AddSingleton <IConfigureOptions <MiniProfilerOptions>, MiniProfilerOptionsDefaults>(); if (configureOptions != null) { services.Configure(configureOptions); } // Set background statics services.Configure <MiniProfilerOptions>(o => MiniProfiler.Configure(o)); // See https://github.com/MiniProfiler/dotnet/issues/162 for plans // Blocked on https://github.com/aspnet/Mvc/issues/6222 //services.AddSingleton<IMiniProfilerDiagnosticListener, MvcViewDiagnosticListener>(); services.AddTransient <IConfigureOptions <MvcOptions>, MiniProfilerSetup>() .AddTransient <IConfigureOptions <MvcViewOptions>, MiniProfilerSetup>(); return(new MiniProfilerBuilder(services)); }
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 static void SetupMiniProfiler() { var options = MiniProfiler.Configure(new MiniProfilerOptions() { RouteBasePath = "~/profiler/", PopupRenderPosition = RenderPosition.Left, PopupMaxTracesToShow = 5, Storage = new MiniProfilerCacheStorage(TimeSpan.FromMinutes(10)), ProfilerProvider = new AspNetRequestProvider(true) }.IgnorePath("/graph") .IgnorePath("/login") .IgnorePath("/spark") .IgnorePath("/top-refresh") .AddViewPofiling() ); Cache.EnableProfiling = SiteSettings.PollerProfiling; Cache.LogExceptions = SiteSettings.LogPollerExceptions; }
public DbMain() { Exports.Add("getConnectionObject", new Func <string, object>(GetConnectionObject)); m_serviceProvider = new ServiceCollection() .AddSingleton <DbFactoryList>() .AddDbTaskFactory <FetchAllFactory>() .AddDbTaskFactory <FetchScalarFactory>() .AddDbTaskFactory <ExecuteFactory>() .AddDbTaskFactory <InsertFactory>() .AddSingleton <DbContext>() .BuildServiceProvider(); MiniProfiler.Configure(new MiniProfilerOptions() { }); m_profiler = MiniProfiler.StartNew("dblyr"); Self = this; }
/// <summary> /// Adds MiniProfiler timings for actions and views. /// </summary> /// <param name="services">The services collection to configure.</param> /// <param name="configureOptions">An Action{MiniProfilerOptions} to configure options for MiniProfiler.</param> public static IMiniProfilerBuilder AddMiniProfiler(this IServiceCollection services, Action <MiniProfilerOptions> configureOptions = null) { services.AddMemoryCache(); // Unconditionally register an IMemoryCache since it's the most common and default case services.AddSingleton <IConfigureOptions <MiniProfilerOptions>, MiniProfilerOptionsDefaults>(); if (configureOptions != null) { services.Configure(configureOptions); } // Set background statics services.Configure <MiniProfilerOptions>(o => MiniProfiler.Configure(o)); // See https://github.com/MiniProfiler/dotnet/issues/162 for plans // Blocked on https://github.com/aspnet/Mvc/issues/6222 //services.AddSingleton<IMiniProfilerDiagnosticListener, MvcViewDiagnosticListener>(); services.AddTransient <IConfigureOptions <MvcOptions>, MiniProfilerSetup>() .AddTransient <IConfigureOptions <MvcViewOptions>, MiniProfilerSetup>(); #if !NETCOREAPP3_0 services.AddTransient <IViewComponentInvokerFactory, ProfilingViewComponentInvokerFactory>(); #endif return(new MiniProfilerBuilder(services)); }
/// <summary> /// Adds MiniProfiler timings for actions and views. /// </summary> /// <param name="services">The services collection to configure.</param> /// <param name="configureOptions">An <see cref="Action{MiniProfilerOptions}"/> to configure options for MiniProfiler.</param> public static IMiniProfilerBuilder AddMiniProfiler(this IServiceCollection services, Action <MiniProfilerOptions> configureOptions = null) { services.AddMemoryCache(); // Unconditionally register an IMemoryCache since it's the most common and default case services.AddSingleton <IConfigureOptions <MiniProfilerOptions>, MiniProfilerOptionsDefaults>(); if (configureOptions != null) { services.Configure(configureOptions); } // Set background statics services.Configure <MiniProfilerOptions>(o => MiniProfiler.Configure(o)); services.AddSingleton <DiagnosticInitializer>(); // For any IMiniProfilerDiagnosticListener registration #if NETCOREAPP3_1 services.AddSingleton <IMiniProfilerDiagnosticListener, MvcDiagnosticListener>(); // For view and action profiling #else services.AddTransient <IConfigureOptions <MvcOptions>, MiniProfilerSetup>() .AddTransient <IConfigureOptions <MvcViewOptions>, MiniProfilerSetup>() .AddTransient <IViewComponentInvokerFactory, ProfilingViewComponentInvokerFactory>(); #endif return(new MiniProfilerBuilder(services)); }
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(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Setup profiler for Controllers via a Global ActionFilter GlobalFilters.Filters.Add(new ProfilingActionFilter()); // initialize automatic view profiling var copy = ViewEngines.Engines.ToList(); ViewEngines.Engines.Clear(); foreach (var item in copy) { ViewEngines.Engines.Add(new ProfilingViewEngine(item)); } MiniProfiler.Configure(new MiniProfilerOptions { RouteBasePath = "~/mini-profiler-resources" }); }
private static void Main(string[] args) { var loggerFactory = LoggerFactory.Create(builder => builder .AddConsole() .AddDebug() .SetMinimumLevel(LogLevel.Trace)); MiniProfiler.Configure(new MiniProfilerOptions { Storage = new LoggerStorage(loggerFactory, LogLevel.Debug) }); var profiler = MiniProfiler.StartNew("Sample Profile"); using (profiler.Step("Many operations")) using (var conn = GetConnection(profiler)) { conn.Query <long>("select 1"); using (profiler.Step("Nested operation")) { conn.Query <long>("select 1"); } using (var wc = new WebClient()) using (profiler.CustomTiming("http", "GET https://google.com")) { wc.DownloadString("https://google.com"); } } profiler.Stop(); Console.ReadKey(); }
/// <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 = MiniProfiler.Configure(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 on that page, and on the right (the application 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).IndexOf("isauthorized", StringComparison.OrdinalIgnoreCase) >= 0); } // 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 .AddViewPofiling() // Add MVC view profiling ); MiniProfilerEF6.Initialize(); }
protected void Application_Start() { MvcHandler.DisableMvcResponseHeader = true; DevExtremeBundleConfig.RegisterBundles(BundleTable.Bundles); DevExpress.Data.Helpers.ServerModeCore.DefaultForceCaseInsensitiveForAnySource = true; DevExpress.XtraReports.Web.ASPxReportDesigner.StaticInitialize(); //Elmah for Web API errors logging GlobalConfiguration.Configuration.Filters.Add(new ElmahHandleErrorApiAttribute()); // Custom Filter / Attribute to override action execution methods //GlobalFilters.Filters.Add(new LogAttribute()); if (GaneStaticAppExtensions.MiniProfilerEnabled) { // mini profiler MiniProfilerEF6.Initialize(); } GlobalFilters.Filters.Add(new StackExchange.Profiling.Mvc.ProfilingActionFilter()); // remove unnecessary view engines ViewEngines.Engines.Clear(); IViewEngine razorEngine = new RazorViewEngine() { FileExtensions = new string[] { "cshtml" } }; ViewEngines.Engines.Add(razorEngine); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //custom Json date formatter JsonMediaTypeFormatter jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter; JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings() { //Formatting = Formatting.Indented, DateTimeZoneHandling = DateTimeZoneHandling.Utc //NullValueHandling = NullValueHandling.Ignore }; jSettings.Converters.Add(new MyDateTimeConvertor()); jsonFormatter.SerializerSettings = jSettings; ModelBinders.Binders.DefaultBinder = new DevExpressEditorsBinder(); // Custom Localizer for Dev Express Scheduler CustomASPxSchedulerLocalizer.Activate(); AutoMapperBootStrapper.RegisterMappings(); MiniProfiler.Configure(new MiniProfilerOptions { // Sets up the route to use for MiniProfiler resources: // Here, ~/profiler is used for things like /profiler/mini-profiler-includes.js RouteBasePath = "~/profiler", // Example of using SQLite storage instead //Storage = new SqliteMiniProfilerStorage(ConnectionString), // 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.Current.RenderIncludes(position: RenderPosition.Left) // ...then the position would be on the left on that page, and on the right (the application 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 => request.IsLocal, // 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 this example }, // Stack trace settings StackMaxLength = 256, // default is 120 characters // (Optional) You can disable "Connection Open()", "Connection Close()" (and async variant) tracking. // (defaults to true, and connection opening/closing is tracked) TrackConnectionOpenClose = true } // Optional settings to control the stack trace output in the details pane, examples: .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 .AddViewProfiling() // Add MVC view profiling (you want this) // If using EntityFrameworkCore, here's where it'd go. // .AddEntityFramework() // Extension method in the MiniProfiler.EntityFrameworkCore package ); }
/// <summary> /// Customize aspects of the MiniProfiler. /// </summary> private void InitProfilerSettings() { // MiniProfiler的一個強大功能是能夠與其他開發人員共享與結果的鏈接。但是,默認情況下,長期結果緩存是在HttpRuntime.Cache中完成的,這是非常不穩定的。 // 讓我們將我們的探查器結果序列化到數據庫中,這樣他們就可以在應用程序重啟後繼續運行。 MiniProfiler.Configure(new MiniProfilerOptions { // 設置用於MiniProfiler資源的路由: // 這裡,〜/ profiler用於/profiler/mini-profiler-includes.js之類的東西 // includes.min.js還需要在web.config的system.webServer->handlers中增加MiniProfiler RouteBasePath = "~/profiler", // 設置MultiStorage提供程序。 這將把結果存儲在MemoryCacheStorage(通常是默認值)和SqlLite中。 Storage = new MultiStorageProvider( new MemoryCacheStorage(new TimeSpan(1, 0, 0)), // RecreateDatabase調用僅用於測試目的,因此我們不會檢查db to source控件。但在這裡我們已經使用實體的sqlite,以便於後續進行查詢 new SqliteMiniProfilerStorage(SQLiteConnectionString).RecreateDatabase("create table IF NOT EXISTS RouteHits(RouteName,HitCount,unique(RouteName))") ), // 不同的RDBMS有不同的方式來聲明sql參數 - SQLite可以理解內聯sql參數就好了。 // 默認情況下,將顯示sql參數。 //SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter(), // 這些設置是可選的,並且都具有默認值。在.RenderIncludes()中指定的任何匹配設置將覆蓋此處指定的應用程序範圍的默認值,例如,如果您同時具有: // PopupRenderPosition = RenderPosition.Right; // 並在頁面中: // @MiniProfiler.Current.RenderIncludes(position: RenderPosition.Left) // ...然後,該位置將位於該頁面的左側,而右側(應用程序默認值)位於.RenderIncludes()調用中未指定位置的任何位置。 PopupRenderPosition = RenderPosition.Right, // defaults to left PopupMaxTracesToShow = 10, // defaults to 15 // ResultsAuthorize(可選 - 默認情況下對所有人開放): // 因為探查器結果可以包含敏感數據(例如顯示參數值的sql查詢),我們可以定義一個函數來授權客戶端查看JSON或整頁結果。 // 我們在http://stackoverflow.com上使用它來檢查請求cookie是否屬於有效的開發人員。 ResultsAuthorize = request => { // 如果您需要在每個請求的基礎上限制性能分析的可見性,則可以實現此操作 // 例如,對於此特定路徑,我們將僅允許在設置查詢參數時進行分析 if ("/MiniProfiler/ResultsAuthorization".Equals(request.Url.LocalPath, StringComparison.OrdinalIgnoreCase)) { return((request.Url.Query).IndexOf("isauthorized", StringComparison.OrdinalIgnoreCase) >= 0); } // 所有其他路徑可以檢查我們的全局切換 return(!DisableProfilingResults); }, // ResultsListAuthorize(可選 - 默認情況下對所有人開放) // 默認情況下,儲存的所有會話的列表都受到限制,您必須返回true以允許它 ResultsListAuthorize = request => { // 如果您需要在每個請求的基礎上限制性能分析列表的可見性,則可以實現此操作 return(true); // 所有要求在我們快樂的世界中都是合法的 }, // Stack trace settings StackMaxLength = 256, // default is 120 characters // (可選) 您可以禁用 "Connection Open()", "Connection Close()" (和異步變數) 追踪 // (默認為true,並追踪連接打開/關閉) TrackConnectionOpenClose = true } // 可選設置,用於控制詳細信息窗格中的堆棧跟踪輸出 .ExcludeType("SessionFactory") // 忽略任何名為SessionFactory的類 .ExcludeAssembly("NHibernate") // 忽略任何名為NHibernate的程序集 .ExcludeMethod("Flush") // 忽略名稱為Flush的任何方法 .AddViewProfiling() // 添加MVC視圖分析 ); 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; },