Beispiel #1
1
 public HomeController()
 {
     DbInitializer.Initialize();
     profiler = MiniProfiler.Current;
     EasternStandardTimeId = "Eastern Standard Time";
     ESTTimeZone = TimeZoneInfo.FindSystemTimeZoneById(EasternStandardTimeId);
 }
Beispiel #2
0
 public override StackExchange.Profiling.MiniProfiler Start(ProfileLevel level)
 {
     _profiler = new StackExchange.Profiling.MiniProfiler(ConsoleProfiling.ProfilingUrl(), level);
     SetProfilerActive(_profiler);
     _profiler.User = ConsoleProfiling.CurrentUser();
     return(_profiler);
 }
 public void Save(StackExchange.Profiling.MiniProfiler profiler)
 {
     if (_logAsLevel == LogLevel.Debug)
     {
         _logger.Debug(profiler.RenderPlainText());
     }
     else if (_logAsLevel == LogLevel.Trace)
     {
         _logger.Trace(profiler.RenderPlainText());
     }
     else if (_logAsLevel == LogLevel.Info)
     {
         _logger.Info(profiler.RenderPlainText());
     }
     else if (_logAsLevel == LogLevel.Warn)
     {
         _logger.Warn(profiler.RenderPlainText());
     }
     else if (_logAsLevel == LogLevel.Error)
     {
         _logger.Error(profiler.RenderPlainText());
     }
     else if (_logAsLevel == LogLevel.Fatal)
     {
         _logger.Fatal(profiler.RenderPlainText());
     }
 }
        private static void EnsureName(MiniProfiler profiler, HttpRequest request)
        {
            // also set the profiler name to Controller/Action or /url
            if (string.IsNullOrWhiteSpace(profiler.Name))
            {
                var rc = request.RequestContext;
                RouteValueDictionary values;

                if (rc != null && rc.RouteData != null && (values = rc.RouteData.Values).Count > 0)
                {
                    var controller = values["Controller"];
                    var action = values["Action"];

                    if (controller != null && action != null)
                        profiler.Name = controller.ToString() + "/" + action.ToString();
                }

                if (string.IsNullOrWhiteSpace(profiler.Name))
                {
                    profiler.Name = request.Url.AbsolutePath ?? string.Empty;
                    if (profiler.Name.Length > 50)
                        profiler.Name = profiler.Name.Remove(50);
                }
            }
        }
Beispiel #5
0
 public void RemoveAll()
 {
     using (MiniProfiler.StepStatic("RedisCache_RemoveAll"))
     {
         TryOnClient(client => client.FlushDb());
     }
 }
        public void Write(MiniProfiler miniProfiler)
        {
            if (miniProfiler != null && miniProfiler.DurationMilliseconds > 50)
            {
                StringBuilder sb = new StringBuilder();

                // Write step times
                if (miniProfiler.Root.HasChildren)
                {
                    var children = miniProfiler.Root.Children;
                    foreach (var child in children)
                    {
                        sb.AppendLine(child.Name + " " + child.DurationMilliseconds);
                    }
                }

                // Write overall request time
                sb.AppendLine(string.Format("{0} {1}\n",
                    miniProfiler.DurationMilliseconds,
                    miniProfiler.Root));

                // Write to file
                try
                {
                    File.AppendAllText(@"c:\temp\out.txt", sb.ToString());
                }
                catch (Exception)
                {
                }
            }
        }
        /// <summary>
        /// Sets <paramref name="profiler"/> to be active (read to start profiling)
        /// This should be called once a new MiniProfiler has been created.
        /// </summary>
        /// <exception cref="ArgumentNullException">If <paramref name="profiler"/> is null</exception>
        protected static void SetProfilerActive(MiniProfiler profiler)
        {
            if (profiler == null)
                throw new ArgumentNullException("profiler");

            profiler.IsActive = true;
        }
Beispiel #8
0
 public void Remove(IEnumerable <string> keys)
 {
     using (MiniProfiler.StepStatic("RedisCache_Remove_" + keys.Count() + "_Keys"))
     {
         TryOnClient(client => client.RemoveAll(keys));
     }
 }
        /// <summary>
        /// Stores <paramref name="profiler"/> under its <see cref="P:StackExchange.Profiling.MiniProfiler.Id"/>.
        /// </summary>
        /// <param name="profiler">The results of a profiling session.</param>
        /// <remarks>
        /// Should also ensure the profiler is stored as being un-viewed by its profiling <see cref="P:StackExchange.Profiling.MiniProfiler.User"/>.
        /// </remarks>
        public void Save(MiniProfiler profiler)
        {
            if (_log == null)
            {
                return;
            }

            switch (_profilerProfilerLevel)
            {
                case Log4NetLevels.Off:
                    //Off
                    return;
                case Log4NetLevels.Fatal:
                    _log.FatalExt(GetProfilerText(profiler));
                    break;
                case Log4NetLevels.Error:
                    _log.ErrorExt(GetProfilerText(profiler));
                    break;
                case Log4NetLevels.Warn:
                    _log.WarnExt(GetProfilerText(profiler));
                    break;
                case Log4NetLevels.Info:
                    _log.InfoExt(GetProfilerText(profiler));
                    break;
                case Log4NetLevels.Debug:
                    _log.DebugExt(GetProfilerText(profiler));
                    break;
            }
        }
Beispiel #10
0
 public void Remove(string key)
 {
     using (MiniProfiler.StepStatic("RedisCache_Remove_" + key))
     {
         TryOnClient(client => client.Remove(key));
     }
 }
Beispiel #11
0
 public bool TryRemove(string key)
 {
     using (MiniProfiler.StepStatic("RedisCache_TryRemove_" + key))
     {
         return(TryOnClient(client => client.Remove(key)));
     }
 }
 public override StackExchange.Profiling.MiniProfiler Start(ProfileLevel level, string sessionName = null)
 {
     _profiler = new StackExchange.Profiling.MiniProfiler(ConsoleProfiling.ProfilingUrl(), level);
     SetProfilerActive(_profiler);
     _profiler.User = ConsoleProfiling.CurrentUser();
     return _profiler;
 }
        public override MiniProfiler Start(ProfileLevel level, string sessionName = null)
        {
            var context = HttpContext.Current;
            if (context == null || context.Request.AppRelativeCurrentExecutionFilePath == null) return null;

            var url = context.Request.Url;
            var path = context.Request.AppRelativeCurrentExecutionFilePath.Substring(1).ToUpperInvariant();

            // don't profile /content or /scripts, either - happens in web.dev
            foreach (var ignored in MiniProfiler.Settings.IgnoredPaths ?? new string[0])
            {
                if (path.Contains((ignored ?? string.Empty).ToUpperInvariant()))
                    return null;
            }

            if (context.Request.Path.StartsWith(VirtualPathUtility.ToAbsolute(MiniProfiler.Settings.RouteBasePath), StringComparison.InvariantCultureIgnoreCase))
            {
                return null;
            }

            var result = new MiniProfiler(sessionName ?? url.OriginalString, level);
            Current = result;

            SetProfilerActive(result);

            // don't really want to pass in the context to MiniProfler's constructor or access it statically in there, either
            result.User = Settings.UserProvider.GetUser(context.Request);

            return result;
        }
Beispiel #14
0
 public bool Exists(string key)
 {
     using (MiniProfiler.StepStatic("RedisCache_Exists_" + key))
     {
         return(TryOnClient(client => client.Exists(key)));
     }
 }
Beispiel #15
0
 public override StackExchange.Profiling.MiniProfiler Start(string sessionName = null)
 {
     _profiler      = new StackExchange.Profiling.MiniProfiler(ConsoleProfiling.ProfilingUrl());
     _profiler.Name = sessionName;
     SetProfilerActive(_profiler);
     _profiler.User = ConsoleProfiling.CurrentUser();
     return(_profiler);
 }
Beispiel #16
0
 public void Save(StackExchange.Profiling.MiniProfiler profiler)
 {
     if (profiler == null)
     {
         return;
     }
     _logger.Log(_logLevel, profiler.ToJson());
 }
Beispiel #17
0
 public void Unlock(string key, IConcurrencyHandle handle)
 {
     using (MiniProfiler.StepStatic("RedisCache_Unlock_" + key))
     {
         var token = ((RedisLockHandle)handle).Token;
         TryOnClient(c => c.Database.LockRelease(key, token));
     }
 }
 /// <summary>
 /// Creates a new profiler for the current context, used for background tasks
 /// </summary>
 /// <param name="name">The name of the profiler to create</param>
 /// <param name="id">The Id of the profiler</param>
 public static MiniProfiler CreateContextProfiler(string name, Guid? id = null)
 {
     var profiler = new MiniProfiler(name);
     SetProfilerActive(profiler);
     if (id.HasValue) profiler.Id = id.Value;
     CallContext.LogicalSetData(LocalContextKey, profiler);
     return profiler;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="BlogController" /> class.
 /// </summary>
 /// <param name="blogRepository">The blog post repository.</param>
 /// <param name="commentRepository">The Disqus comment repository</param>
 /// <param name="urlShortener">The URL shortener</param>
 /// <param name="socialManager">The social network manager used to get sharing URLs</param>
 /// <param name="siteConfig">Site configuration</param>
 public BlogController(IBlogRepository blogRepository, IDisqusCommentRepository commentRepository, IUrlShortener urlShortener, ISocialManager socialManager, ISiteConfiguration siteConfig)
 {
     _blogRepository = blogRepository;
     _commentRepository = commentRepository;
     _urlShortener = urlShortener;
     _socialManager = socialManager;
     _siteConfig = siteConfig;
     _profiler = MiniProfiler.Current;
 }
 /// <summary>
 /// Calls <see cref="MiniProfiler.Settings.EnsureStorageStrategy"/> to save the current
 /// profiler using the current storage settings
 /// </summary>
 protected static void SaveProfiler(MiniProfiler current)
 {
     // because we fetch profiler results after the page loads, we have to put them somewhere in the meantime
     MiniProfiler.Settings.EnsureStorageStrategy();
     MiniProfiler.Settings.Storage.Save(current);
     if (current.HasUserViewed == false)
     {
         MiniProfiler.Settings.Storage.SetUnviewed(current.User, current.Id);
     }
 }
        /// <summary>
        /// Stops the profiler and marks it as inactive.
        /// </summary>
        /// <returns>True if successful, false if Stop had previously been called on this profiler</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="profiler"/> is null</exception>
        protected static bool StopProfiler(MiniProfiler profiler)
        {
            if (profiler == null)
                throw new ArgumentNullException("profiler");

            if (!profiler.StopImpl())
                return false;

            profiler.IsActive = false;
            return true;
        }
Beispiel #22
0
 public T Get <T>(string key) where T : class
 {
     using (MiniProfiler.StepStatic("RedisCache_Get_" + key))
     {
         return(TryOnClient(client =>
         {
             return client.Get <T>(key);
         }
                            ));
     }
 }
        public void GetProfiler()
        {
            var expectedProfiler = new MiniProfiler("http://fake");
            var storage = NSubstitute.Substitute.For<IStorage>();
            storage.Load(expectedProfiler.Id).Returns(expectedProfiler);

            MiniProfiler.Settings.Storage = storage;

            var controller = new ProfilerResultsController();
            var profiler = controller.Get(expectedProfiler.Id);

            Assert.AreEqual<MiniProfiler>(expectedProfiler, profiler);
        }
        public ProfilerResultViewModel(Profiler profiler)
        {
            Name = profiler.Name;
            MachineName = profiler.MachineName;
            Started = profiler.Started;

            Timings = profiler.GetTimingHierarchy().ToList();

            CustomTimingCommand = new SimpleCommand(_ =>
            {
                CustomTimingsOpen = true;
            });
        }
Beispiel #25
0
        /// <summary>
        /// Returns a new CustomTiming, also initializing its <see cref="Id"/> and, optionally, its <see cref="StackTraceSnippet"/>.
        /// </summary>
        public CustomTiming(MiniProfiler profiler, string commandString)
        {
            _profiler = profiler;
            _startTicks = profiler.ElapsedTicks;
            CommandString = commandString;

            Id = Guid.NewGuid();
            StartMilliseconds = profiler.GetRoundedMilliseconds(profiler.ElapsedTicks);

            if (!MiniProfiler.Settings.ExcludeStackTraceSnippetFromCustomTimings)
            {
                StackTraceSnippet = Helpers.StackTraceSnippet.Get();
            }
        }
        public void GetAllProfilerIdsWithDefaultParams()
        {
            var expectedProfilerIds = new List<Guid>();
            var profiler = new MiniProfiler("http://fake");
            expectedProfilerIds.Add(profiler.Id);
            var storage = NSubstitute.Substitute.For<IStorage>();
            storage.List(25).Returns(expectedProfilerIds);

            MiniProfiler.Settings.Storage = storage;
            
            var controller = new ProfilerResultsController();
            var profilerIds = controller.Get().ToList();

            Assert.AreEqual<Guid>(expectedProfilerIds.First(), profilerIds.First());
        }
Beispiel #27
0
        /// <summary>
        /// Creates a new Timing named 'name' in the 'profiler's session, with 'parent' as this Timing's immediate ancestor.
        /// </summary>
        public Timing(MiniProfiler profiler, Timing parent, string name)
        {
            this.Id = Guid.NewGuid();
            Profiler = profiler;
            Profiler.Head = this;

            if (parent != null) // root will have no parent
            {
                parent.AddChild(this);
            }

            Name = name;
            _startTicks = profiler.ElapsedTicks;
            StartMilliseconds = profiler.GetRoundedMilliseconds(_startTicks);
        }
        /// <summary>
        /// Starts a new MiniProfiler and sets it to be current.  By the end of this method
        ///             <see cref="M:StackExchange.Profiling.BaseProfilerProvider.GetCurrentProfiler"/> should return the new MiniProfiler.
        /// </summary>
        public override MiniProfiler Start(string sessionName = null)
        {
            _profiler = new MiniProfiler(sessionName ?? AppDomain.CurrentDomain.FriendlyName);
            if (IsLogEnabled(_logger, _profilerLogLevel))
            {
                SetProfilerActive(_profiler);
            }
            else
            {
                StopProfiler(_profiler);
            }


            return _profiler;
        }
 /// <summary>
 /// Calls <see cref="MiniProfiler.Settings.EnsureStorageStrategy"/> to save the current
 /// profiler using the current storage settings. 
 /// If <see cref="MiniProfiler.Storage"/> is set, this will be used.
 /// </summary>
 protected static void SaveProfiler(MiniProfiler current)
 {
     // because we fetch profiler results after the page loads, we have to put them somewhere in the meantime
     // If the current MiniProfiler object has a custom IStorage set in the Storage property, use it. Else use the Global Storage.
     var storage = current.Storage;
     if (storage == null)
     {
         MiniProfiler.Settings.EnsureStorageStrategy();
         storage = MiniProfiler.Settings.Storage;
     }
     storage.Save(current);
     if (current.HasUserViewed == false)
     {
         storage.SetUnviewed(current.User, current.Id);
     }
 }
Beispiel #30
0
        /// <summary>
        /// Initialises a new instance of the <see cref="SqlTiming"/> class. 
        /// Creates a new <c>SqlTiming</c> to profile 'command'.
        /// </summary>
        public SqlTiming(IDbCommand command, SqlExecuteType type, MiniProfiler profiler)
        {
            if (profiler == null) throw new ArgumentNullException("profiler");
            _profiler = profiler;
            
            var commandText = AddSpacesToParameters(command.CommandText);
            var parameters = GetCommandParameters(command);

            if (MiniProfiler.Settings.SqlFormatter != null)
            {
                commandText = MiniProfiler.Settings.SqlFormatter.GetFormattedSql(commandText, parameters, command);
            }

            _customTiming = profiler.CustomTiming("sql", commandText, type.ToString());
            if (_customTiming == null) throw new InvalidOperationException();
        }
Beispiel #31
0
        /// <summary>
        /// Initialises a new instance of the <see cref="Suppression"/> class. 
        /// Creates a new Suppression to deactive profiling while alive
        /// </summary>
        public Suppression(MiniProfiler profiler)
        {
            if (profiler == null)
            {
                throw new ArgumentNullException("profiler");
            }

            Profiler = profiler;
            if (!Profiler.IsActive)
            {
                return;
            }

            Profiler.IsActive = false;
            _wasSuppressed = true;
        }
        public static DbConnection GetConnection(MiniProfiler profiler = null)
        {
            using (profiler.Step("GetOpenConnection"))
            {
                DbConnection cnn = new System.Data.SQLite.SQLiteConnection(MvcApplication.ConnectionString);

                // to get profiling times, we have to wrap whatever connection we're using in a ProfiledDbConnection
                // when MiniProfiler.Current is null, this connection will not record any database timings
                if (MiniProfiler.Current != null)
                {
                    cnn = new StackExchange.Profiling.Data.ProfiledDbConnection(cnn, MiniProfiler.Current);
                }

                cnn.Open();
                return cnn;
            }
        }
        public void HandlerShouldAddProfileLocationHeader()
        {
            var profiler = new MiniProfiler("http://fake");
            var config = new HttpConfiguration();
            var route = config.Routes.MapHttpRoute("Profiler", "profiler/results/{id}", new { controller = "ProfilerResultsController" });
            var innerhandler = new FakeDelegatingHandler();
            innerhandler.Message = new HttpResponseMessage(HttpStatusCode.OK);
            var client = new HttpMessageInvoker(new ProfilerMessageHandler(route, profiler) { InnerHandler = innerhandler });
            var requestMessage = new HttpRequestMessage(HttpMethod.Get, "http://fake/test");
            requestMessage.SetConfiguration(config);
            
            var message = client.SendAsync(requestMessage, new CancellationToken(false)).Result;
            
            Assert.IsTrue(message.Headers.Contains(Constants.ProfilerResultsHeaderName), "HTTP Header {0} was not found in collection", Constants.ProfilerResultsHeaderName);
            var headerValue = message.Headers.GetValues(Constants.ProfilerResultsHeaderName).First();
            Assert.AreEqual<string>("http://fake/profiler/results/" + profiler.Id, headerValue, "Didn't receive expected header value");

        }
        /// <summary>
        /// Adds the profiling results fro the <paramref name="response"/> to the supplied <paramref name="profiler"/>.
        /// </summary>
        /// <param name="response">The response from a request.</param>
        /// <param name="profiler">The profiler to add the results to.</param>
        /// <param name="newStartMilliseconds">The start time used to update the remote timings.</param>
        internal static HttpResponseMessage AddRemoteProfilerResults(HttpResponseMessage response, MiniProfiler profiler, decimal newStartMilliseconds)
        {
            // Get the serialized results header.
            IEnumerable<string> miniProfilerResults;
            if (!response.Headers.TryGetValues(MiniProfilerHandler.ResultsHeaderName, out miniProfilerResults))
                return response;

            // Get the data.
            string resultsHeader = miniProfilerResults.First();
            MiniProfiler remoteProfiler = ProfilerExtensions.Deserialize(resultsHeader);

            // Update the timings of the remote profiler results.
            remoteProfiler.Root.UpdateStartMillisecondTimingsToAbsolute(newStartMilliseconds);

            profiler.AddProfilerResults(remoteProfiler);

            return response;
        }
Beispiel #35
0
        /// <summary>
        /// Creates a new Timing named 'name' in the 'profiler's session, with 'parent' as this Timing's immediate ancestor.
        /// </summary>
        public Timing(MiniProfiler profiler, Timing parent, string name, decimal? minSaveMs = null, bool? includeChildrenWithMinSave = false)
        {
            Id = Guid.NewGuid();
            Profiler = profiler;
            Profiler.Head = this;

            if (parent != null)
            {
                // root will have no parent
                parent.AddChild(this);
            }

            Name = name;

            _startTicks = profiler.ElapsedTicks;
            _minSaveMs = minSaveMs;
            _includeChildrenWithMinSave = includeChildrenWithMinSave == true;
            StartMilliseconds = profiler.GetRoundedMilliseconds(_startTicks);
        }
Beispiel #36
0
        /// <summary>
        /// Initialises a new instance of the <see cref="SqlTiming"/> class. 
        /// Creates a new <c>SqlTiming</c> to profile 'command'.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="type">The type.</param>
        /// <param name="profiler">The profiler.</param>
        public SqlTiming(IDbCommand command, ExecuteType type, MiniProfiler profiler)
        {
            Id = Guid.NewGuid();

            CommandString = AddSpacesToParameters(command.CommandText);
            Parameters = GetCommandParameters(command);
            ExecuteType = type;

            if (!MiniProfiler.Settings.ExcludeStackTraceSnippetFromSqlTimings)
                StackTraceSnippet = Helpers.StackTraceSnippet.Get();

            _profiler = profiler;
            if (_profiler != null)
            {
                _profiler.AddSqlTiming(this);
                _startTicks = _profiler.ElapsedTicks;
                StartMilliseconds = _profiler.GetRoundedMilliseconds(_startTicks);
            }
        }
Beispiel #37
0
 public void Set <T>(string key, T value, IConcurrencyHandle handle) where T : class
 {
     using (MiniProfiler.StepStatic("RedisCache_SetConcurrent_" + key))
     {
         TryOnClient(c =>
         {
             if (c.Database.LockTake(key, ((RedisLockHandle)handle).Token, TimeSpan.FromSeconds(1)))
             {
                 try
                 {
                     c.Add <object>(key, value, TimeSpan.FromHours(1));
                 }
                 finally
                 {
                     c.Database.LockRelease(key, ((RedisLockHandle)handle).Token);
                 }
             }
         });
     }
 }
Beispiel #38
0
        public bool TryGet <T>(string key, ref T value) where T : class
        {
            using (MiniProfiler.StepStatic("RedisCache_TryGet_" + key))
            {
                T   val    = default(T);
                var result = TryOnClient((client) =>
                {
                    val = client.Get <T>(key);
                    if (val == null)
                    {
                        return(false);
                    }
                    return(true);
                });

                value = val;

                return(result);
            }
        }
        private void UpsertRouteHit(ActionDescriptor actionDesc, MiniProfiler profiler)
        {
            var routeName = actionDesc.ControllerDescriptor.ControllerName + "/" + actionDesc.ActionName;

            using (var conn = GetConnection(profiler))
            {
                var param = new { routeName = routeName };

                using (profiler.Step("Insert RouteHits"))
                {
                   conn.Execute("insert or ignore into RouteHits (RouteName, HitCount) values (@routeName, 0)", param);
                }
                using (profiler.Step("Update RouteHits"))
                {
                    // let's put some whitespace in this query to demonstrate formatting
                    conn.Execute(
            @"update RouteHits
            set    HitCount = HitCount + 1
            where  RouteName = @routeName", param);
                }
            }
        }
Beispiel #40
0
        public T Get <T>(string key, out IConcurrencyHandle handle)
            where T : class, new()
        {
            using (MiniProfiler.StepStatic("RedisCache_GetConcurrent_" + key))
            {
                var token       = this.GetType().ToString();
                var retryPolicy = new LockRetryPolicy();

                var result = TryOnClient(c =>
                {
                    T item = default(T);
                    retryPolicy.Handle(() =>
                    {
                        if (c.Database.LockTake(key, token, TimeSpan.FromSeconds(1)))
                        {
                            try
                            {
                                object obj = c.Get <object>(key);
                                item       = (T)obj;
                            }
                            finally
                            {
                                c.Database.LockRelease(key, token);
                            }
                        }
                    });
                    return(item);
                });

                handle = new RedisLockHandle
                {
                    Token = token
                };

                return(result);
            }
        }
        public override MiniProfiler Start(ProfileLevel level)
        {
            var context = WcfInstanceContext.Current;
            if (context == null) return null;

            var operationContext = OperationContext.Current;
            if (operationContext == null) return null;

            var instanceContext = operationContext.InstanceContext;
            if (instanceContext == null) return null;

            var webOperationContext = WebOperationContext.Current;
            if((webOperationContext == null) == true) return null;
            if (webOperationContext.IncomingRequest.UriTemplateMatch == null) return null;

            var result = new MiniProfiler(GetProfilerName(operationContext, instanceContext), level);
            result.Root.AddKeyValue("requesturl",operationContext.IncomingMessageHeaders.To.OriginalString);
            result.Root.AddKeyValue("method", webOperationContext.IncomingRequest.Method);

            SetCurrentProfiler(result);
            SetProfilerActive(result);

            return result;
        }
Beispiel #42
0
 /// <summary>
 /// Renders the parameter <see cref="MiniProfiler"/> to JSON.
 /// </summary>
 public static string ToJson(MiniProfiler profiler)
 {
     return profiler == null ? null : GetJsonSerializer().Serialize(profiler);
 }
 /// <summary>
 /// Starts a new profiling session.
 /// </summary>
 /// <param name="profilerName">The name for the started <see cref="MiniProfiler"/>.</param>
 /// <param name="options">The options to use for this profiler, including all downstream commands.</param>
 public MiniProfiler Start(string profilerName, MiniProfilerBaseOptions options) =>
 _profiler = new MiniProfiler(profilerName, options);
Beispiel #44
0
 /// <summary>
 /// Returns an <see cref="Timing"/> (<see cref="IDisposable"/>) that will time the code between its creation and disposal.
 /// </summary>
 /// <param name="profiler">The current profiling session or null.</param>
 /// <param name="name">A descriptive name for the code that is encapsulated by the resulting Timing's lifetime.</param>
 /// <returns>the profile step</returns>
 public static Timing Step(this MiniProfiler profiler, string name) => profiler?.StepImpl(name);
Beispiel #45
0
        /// <summary>
        /// Renders the parameter <see cref="MiniProfiler"/> to JSON.
        /// </summary>
        /// <param name="profiler">The profiler.</param>
        /// <returns>a string containing the JSON result.</returns>
        public static string ToJson(MiniProfiler profiler)
        {
            if (profiler == null) return null;

            var result = new JavaScriptSerializer { MaxJsonLength = Settings.MaxJsonResponseSize }.Serialize(profiler);
            return result;
        }
Beispiel #46
0
 private string ResultsFullPage(HttpContext context, MiniProfiler profiler)
 {
     context.Response.ContentType = "text/html";
     return(Render.SingleResultHtml(profiler, VirtualPathUtility.ToAbsolute(Options.RouteBasePath).EnsureTrailingSlash()));
 }
 private string ResultsFullPage(HttpContext context, MiniProfiler profiler)
 {
     context.Response.ContentType = "text/html";
     return(profiler.RenderResultsHtml(Current.BasePath.Value));
 }
Beispiel #48
0
 public Task StoppedAsync(StackExchange.Profiling.MiniProfiler profiler, bool discardResults)
 {
     return(provider.StoppedAsync(profiler, discardResults));
 }
Beispiel #49
0
 private static string ResultsJson(HttpContext context, MiniProfiler profiler)
 {
     context.Response.ContentType = "application/json";
     return(profiler.ToJson());
 }
Beispiel #50
0
 /// <summary>
 /// Returns an <see cref="IDisposable"/> that will ignore profiling between its creation and disposal.
 /// </summary>
 /// <remarks>
 /// This is mainly useful in situations where you want to ignore database profiling for known hot spots,
 /// but it is safe to use in a nested step such that you can ignore sub-sections of a profiled step.
 /// </remarks>
 /// <param name="profiler">The current profiling session or null.</param>
 /// <returns>the profile step</returns>
 public static IDisposable Ignore(this MiniProfiler profiler) => profiler != null ? new Suppression(profiler) : null;
Beispiel #51
0
 public void Stopped(StackExchange.Profiling.MiniProfiler profiler, bool discardResults)
 {
     provider.Stopped(profiler, discardResults);
 }
 /// <summary>
 /// Asynchronously stops the current profiling session.
 /// </summary>
 /// <param name="profiler">The <see cref="MiniProfiler"/> to stop.</param>
 /// <param name="discardResults">
 /// When true, clears the <see cref="MiniProfiler.Current"/>, allowing profiling to
 /// be prematurely stopped and discarded. Useful for when a specific route does not need to be profiled.
 /// </param>
 public Task StoppedAsync(MiniProfiler profiler, bool discardResults)
 {
     Stopped(profiler, discardResults);
     return(Task.CompletedTask);
 }
Beispiel #53
0
 /// <summary>
 /// Returns an <see cref="IDisposable"/> that will ignore profiling between its creation and disposal.
 /// </summary>
 /// <remarks>
 /// This is mainly useful in situations where you want to ignore database profiling for known hot spots,
 /// but it is safe to use in a nested step such that you can ignore sub-sections of a profiled step.
 /// </remarks>
 /// <param name="profiler">The current profiling session or null.</param>
 /// <returns>the profile step</returns>
 public static IDisposable Ignore(this MiniProfiler profiler)
 {
     return(profiler == null ? null : profiler.IgnoreImpl());
 }
 /// <summary>
 /// Returns a new <c>SqlProfiler</c> to be used in the <paramref name="profiler"/> session.
 /// </summary>
 public SqlProfiler(MiniProfiler profiler)
 {
     Profiler = profiler;
 }
Beispiel #55
0
 /// <summary>
 /// Returns an <see cref="Timing"/> (<see cref="IDisposable"/>) that will time the code between its creation and disposal.
 /// Will only save the <see cref="Timing"/> if total time taken exceeds <paramref name="minSaveMs" />.
 /// </summary>
 /// <param name="profiler">The current profiling session or <c>null</c>.</param>
 /// <param name="name">A descriptive name for the code that is encapsulated by the resulting Timing's lifetime.</param>
 /// <param name="minSaveMs">The minimum amount of time that needs to elapse in order for this result to be recorded.</param>
 /// <param name="includeChildren">Should the amount of time spent in child timings be included when comparing total time
 /// profiled with <paramref name="minSaveMs"/>? If true, will include children. If false will ignore children.</param>
 /// <returns></returns>
 /// <remarks>If <paramref name="includeChildren"/> is set to true and a child is removed due to its use of StepIf, then the
 /// time spent in that time will also not count for the current StepIf calculation.</remarks>
 public static Timing StepIf(this MiniProfiler profiler, string name, decimal minSaveMs, bool includeChildren = false)
 {
     return(profiler?.StepImpl(name, minSaveMs, includeChildren));
 }
Beispiel #56
0
 /// <summary>
 /// Returns a plain-text representation of <paramref name="profiler"/>, suitable for viewing from
 /// <see cref="Console"/>, log, or unit test output.
 /// </summary>
 /// <param name="profiler">A profiling session with child <see cref="Timing"/> instances.</param>
 public static string RenderPlainText(this MiniProfiler profiler)
 {
     return(RenderImpl(profiler, false));
 }
        private void RecursiveMethod(ref int i, DbConnection conn, MiniProfiler profiler)
        {
            Thread.Sleep(5); // ensure we show up in the profiler

            if (i >= 10) return;

            using (profiler.Step("Nested call " + i))
            {
                // run some meaningless queries to illustrate formatting
                conn.Query(
            @"select *
            from   MiniProfilers
            where  Name like @name
            or Name = @name
            or DurationMilliseconds >= @duration
            or HasSqlTimings = @hasSqlTimings
            or Started > @yesterday ", new
                                 {
                                     name = "Home/Index",
                                     duration = 100.5,
                                     hasSqlTimings = true,
                                     yesterday = DateTime.UtcNow.AddDays(-1)
                                 });

                conn.Query(@"select RouteName, HitCount from RouteHits where HitCount < 100000000 or HitCount > 0 order by HitCount, RouteName -- this should hopefully wrap");

                // massive query to test if max-height is properly removed from <pre> stylings
                conn.Query(
            @"select *
            from   (select RouteName,
               HitCount
            from   RouteHits
            where  HitCount between 0 and 9
            union all
            select RouteName,
               HitCount
            from   RouteHits
            where  HitCount between 10 and 19
            union all
            select RouteName,
               HitCount
            from   RouteHits
            where  HitCount between 20 and 29
            union all
            select RouteName,
               HitCount
            from   RouteHits
            where  HitCount between 30 and 39
            union all
            select RouteName,
               HitCount
            from   RouteHits
            where  HitCount between 40 and 49
            union all
            select RouteName,
               HitCount
            from   RouteHits
            where  HitCount between 50 and 59
            union all
            select RouteName,
               HitCount
            from   RouteHits
            where  HitCount between 60 and 69
            union all
            select RouteName,
               HitCount
            from   RouteHits
            where  HitCount between 70 and 79
            union all
            select RouteName,
               HitCount
            from   RouteHits
            where  HitCount between 80 and 89
            union all
            select RouteName,
               HitCount
            from   RouteHits
            where  HitCount between 90 and 99
            union all
            select RouteName,
               HitCount
            from   RouteHits
            where  HitCount > 100)
            order  by RouteName");

                using (profiler.Step("Incrementing a reference parameter named i")) // need a long title to test max-width
                {
                    i++;
                }
                RecursiveMethod(ref i, conn, profiler);
            }
        }
 /// <summary>
 /// Renders the parameter <see cref="MiniProfiler"/> to JSON.
 /// </summary>
 public static string ToJson(MiniProfiler profiler)
 {
     return(profiler == null ? null : GetJsonSerializer().Serialize(profiler));
 }
 /// <summary>
 /// Returns an <see cref="IDisposable"/> that will time the code between its creation and disposal.
 /// </summary>
 /// <param name="profiler">The current profiling session or null.</param>
 /// <param name="name">A descriptive name for the code that is encapsulated by the resulting IDisposable's lifetime.</param>
 /// <param name="level">This step's visibility level; allows filtering when <see cref="MiniProfiler.Start"/> is called.</param>
 public static IDisposable Step(this MiniProfiler profiler, string name, ProfileLevel level = ProfileLevel.Info)
 {
     return(profiler == null ? null : profiler.StepImpl(name, level));
 }
Beispiel #60
0
 /// <summary>
 /// Returns a new <see cref="CustomTiming"/> that will automatically set its <see cref="Profiling.CustomTiming.StartMilliseconds"/>
 /// and <see cref="Profiling.CustomTiming.DurationMilliseconds"/>
 /// </summary>
 /// <param name="profiler">The current profiling session or null.</param>
 /// <param name="category">The category under which this timing will be recorded.</param>
 /// <param name="commandString">The command string that will be recorded along with this timing, for display in the MiniProfiler results.</param>
 /// <param name="executeType">Execute Type to be associated with the Custom Timing. Example: Get, Set, Insert, Delete</param>
 /// <remarks>
 /// Should be used like the <see cref="Step(MiniProfiler, string)"/> extension method
 /// </remarks>
 public static CustomTiming CustomTiming(this MiniProfiler profiler, string category, string commandString, string executeType = null)
 {
     return(CustomTimingIf(profiler, category, commandString, 0, executeType: executeType));
 }