/// <summary>
        /// Formats the SQL in a SQL-Server friendly way, with DECLARE statements for the parameters up top.
        /// </summary>
        /// <param name="commandText">The SQL command to format.</param>
        /// <param name="parameters">The parameters for the SQL command.</param>
        /// <param name="command">The <see cref="IDbCommand"/> being represented.</param>
        public override string FormatSql(string commandText, List <SqlTimingParameter> parameters, IDbCommand command = null)
        {
            var buffer = StringBuilderCache.Get();

            if (command != null && IncludeMetaData)
            {
                buffer.Append("-- Command Type: ").Append(command.CommandType.ToString()).Append("\n");
                buffer.Append("-- Database: ").Append(command.Connection.Database).Append("\n");

                if (command.Transaction != null)
                {
                    buffer.Append("-- Command Transaction Iso Level: ").Append(command.Transaction.IsolationLevel.ToString()).Append("\n");
                }
                if (System.Transactions.Transaction.Current != null)
                {
                    // transactions issued by TransactionScope are not bound to the database command but exists globally
                    buffer.Append("-- Transaction Scope Iso Level: ").Append(System.Transactions.Transaction.Current.IsolationLevel.ToString()).Append("\n");
                }

                buffer.Append("\n");
            }

            string baseOutput = base.FormatSql(commandText, parameters, command);

            buffer.Append(baseOutput);

            return(buffer.ToStringRecycle());
        }
Beispiel #2
0
        private void EnsureName(MiniProfiler profiler, HttpContext context)
        {
            if (profiler.Name == nameof(MiniProfiler))
            {
                var url = StringBuilderCache.Get()
                          .Append(context.Request.Scheme)
                          .Append("://")
                          .Append(context.Request.Host.Value)
                          .Append(context.Request.PathBase.Value)
                          .Append(context.Request.Path.Value)
                          .Append(context.Request.QueryString.Value)
                          .ToStringRecycle();

                var routeData = (context.Features[typeof(IRoutingFeature)] as IRoutingFeature)?.RouteData;
                if (routeData != null)
                {
                    profiler.Name = routeData.Values["controller"] + "/" + routeData.Values["action"];
                }
                else
                {
                    profiler.Name = url;
                    if (profiler.Name.Length > 50)
                    {
                        profiler.Name = profiler.Name.Remove(50);
                    }
                }
                if (profiler.Root?.Name == nameof(MiniProfiler))
                {
                    profiler.Root.Name = url;
                }
            }
        }
Beispiel #3
0
        private string RenderVariableTable(string title, NameValueCollection vars)
        {
            if (vars == null || vars.Count == 0)
            {
                return(string.Empty);
            }
            Func <string, bool> isHidden = k => DefaultHttpKeys.Contains(k);
            var allKeys = vars.AllKeys.Where(key => !HiddenHttpKeys.Contains(key) && vars[key].HasValue()).OrderBy(k => k);

            var sb = StringBuilderCache.Get();

            sb.Append("h3.").AppendLine(title);
            sb.AppendLine("{noformat}");
            foreach (var k in allKeys.Where(k => !isHidden(k)))
            {
                sb.AppendFormat("{0}: {1}\r\n", k, vars[k]);
            }
            if (vars["HTTP_HOST"].HasValue() && vars["URL"].HasValue())
            {
                var ssl = vars["HTTP_X_FORWARDED_PROTO"] == "https" || vars["HTTP_X_SSL"].HasValue() || vars["HTTPS"] == "on";
                var url = string.Format("http{3}://{0}{1}{2}", vars["HTTP_HOST"], vars["URL"], vars["QUERY_STRING"].HasValue() ? "?" + vars["QUERY_STRING"] : "", ssl ? "s" : "");

                sb.AppendFormat("Request and URL: {0}\r\n", url);
            }

            sb.AppendLine("{noformat}");
            return(sb.ToStringRecycle());
        }
Beispiel #4
0
        private string RenderDescription(Error error, string accountName)
        {
            var sb = StringBuilderCache.Get();

            sb.AppendLine("{noformat}");
            if (accountName.HasValue())
            {
                sb.AppendFormat("Reporter Account Name: {0}\r\n", accountName);
            }
            sb.AppendFormat("Error Guid: {0}\r\n", error.GUID.ToString());
            sb.AppendFormat("App. Name: {0}\r\n", error.ApplicationName);
            sb.AppendFormat("Machine Name: {0}\r\n", error.MachineName);
            sb.AppendFormat("Host: {0}\r\n", error.Host);
            sb.AppendFormat("Created On (UTC): {0}\r\n", error.CreationDate.ToString(CultureInfo.CurrentCulture));
            sb.AppendFormat("Url: {0}\r\n", error.Url);
            sb.AppendFormat("HTTP Method: {0}\r\n", error.HTTPMethod);
            sb.AppendFormat("IP Address: {0}\r\n", error.IPAddress);
            sb.AppendFormat("Count: {0}\r\n", error.DuplicateCount.ToString());

            sb.AppendLine("{noformat}");
            sb.AppendLine("{noformat}");
            sb.AppendLine(error.Detail);
            sb.AppendLine("{noformat}");

            return(sb.ToStringRecycle());
        }
Beispiel #5
0
        private string GetDeclareStatement(QueryPlanType queryPlan)
        {
            if (queryPlan?.ParameterList == null || queryPlan.ParameterList.Length == 0)
            {
                return("");
            }

            var result        = StringBuilderCache.Get();
            var paramTypeList = paramRegex.Match(StatementText);

            if (!paramTypeList.Success)
            {
                return("");
            }
            // TODO: get test cases and move this to a single multi-match regex
            var paramTypes = paramSplitRegex.Split(paramTypeList.Groups[1].Value).Select(p => p.Split(StringSplits.Space));

            foreach (var p in queryPlan.ParameterList)
            {
                var paramType = paramTypes.FirstOrDefault(pt => pt[0] == p.Column);
                if (paramType != null)
                {
                    result.AppendFormat(declareFormat, p.Column, paramType[1], p.ParameterCompiledValue)
                    .AppendLine();
                }
            }
            return(result.Length > 0 ? result.Insert(0, "-- Compiled Params\n").ToStringRecycle() : result.ToStringRecycle());
        }
Beispiel #6
0
        protected override string GetMonitorStatusReason()
        {
            var reason = HealthStatus.Data?.Indexes?.Values.GetReasonSummary();

            if (reason.HasValue())
            {
                return(reason);
            }

            var sb = StringBuilderCache.Get();

            foreach (var node in KnownNodes)
            {
                if (node.LastException != null)
                {
                    sb.Append(node.Name.IsNullOrEmptyReturn(node.Host))
                    .Append(": ")
                    .Append(node.LastException.Message)
                    .Append("; ");
                }
            }

            if (sb.Length > 2)
            {
                sb.Length -= 2;
            }

            return(sb.ToStringRecycle());
        }
        public static IHtmlString GetQueryString(SQLInstance.TopSearchOptions options)
        {
            var sb = StringBuilderCache.Get();

            if (options.MinExecs != Default.MinExecs)
            {
                sb.Append("&").Append(nameof(options.MinExecs)).Append("=").Append(options.MinExecs.Value);
            }
            if (options.MinExecsPerMin != Default.MinExecsPerMin)
            {
                sb.Append("&").Append(nameof(options.MinExecsPerMin)).Append("=").Append(options.MinExecsPerMin.Value);
            }
            if (options.Search != Default.Search)
            {
                sb.Append("&").Append(nameof(options.Search)).Append("=").Append(options.Search.UrlEncode());
            }
            if (options.Database != Default.Database)
            {
                sb.Append("&").Append(nameof(options.Database)).Append("=").Append(options.Database.Value);
            }
            if (options.LastRunSeconds != Default.LastRunSeconds)
            {
                sb.Append("&").Append(nameof(options.LastRunSeconds)).Append("=").Append(options.LastRunSeconds.Value);
            }

            return(sb.ToStringRecycle().AsHtml());
        }
Beispiel #8
0
        /// <summary>
        /// Get the complete string representation and objects to bind to the query.
        /// </summary>
        public void Build()
        {
            _build = false;

            // initialize the string builder
            _builder = StringBuilderCache.Get();

            if (_query.Keywords.Count == 0)
            {
                Log.Warning("Query contains zero commands.");
            }
            else
            {
                switch (_query.Keywords[_keywordIndex])
                {
                case Cql.Select:
                    ++_keywordIndex;
                    ConstructSelect();
                    break;

                case Cql.Update:
                    ++_keywordIndex;
                    ConstructUpdate();
                    break;

                case Cql.Insert:
                    ++_keywordIndex;
                    ConstructInsert();
                    break;

                case Cql.Delete:
                    ++_keywordIndex;
                    ConstructDelete();
                    break;

                case Cql.Create:
                    ++_keywordIndex;
                    switch (_query.Keywords[_keywordIndex])
                    {
                    case Cql.Table:
                        ++_keywordIndex;
                        ConstructCreateTable();
                        break;

                    default:
                        Log.Warning("Unexpected initial command type '" + _query.Keywords[0] + "'.");
                        break;
                    }

                    break;

                default:
                    Log.Warning("Unexpected initial command type '" + _query.Keywords[0] + "'.");
                    break;
                }
            }

            _queryString = StringBuilderCache.SetAndGet(_builder);
            _builder     = null;
        }
Beispiel #9
0
        /// <summary>
        /// Initialize default identities.
        /// </summary>
        protected static void Initialize()
        {
            // add default identities
            Identity identity = new Identity(true);

            identity.Add("Accept", "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/msword, */*");
            identity.Add("User-Agent", "Mozilla/5.0 (compatible; Konqueror/3.5; Linux; X11; i686; en_US) KHTML/3.5.3 (like Gecko)");
            identity.Add("Accept-Language", "en-US,en;q=0.5");
            identity.Add("If-None-Match", "mJ4imx1p");

            identity = new Identity(true);
            identity.Add("Accept", "text/html, application/xml;q=0.9, application/xhtml xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1");
            identity.Add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Version/3.1 Safari/525.13");
            identity.Add("Accept-Language", "en-US,en;q=0.5");
            identity.Add("If-None-Match", "g2ed3k5u");

            identity = new Identity(true);
            identity.Add("Accept", "text/html, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1");
            identity.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1");
            identity.Add("Accept-Language", "en-US,en;q=0.5");
            identity.Add("If-None-Match", "34vn9p8m");

            identity = new Identity(true);
            identity.Add("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
            identity.Add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.11) Gecko/20101023 Firefox/3.6.11 (Palemoon/3.6.11) ( .NET CLR 3.5.30729; .NET4.0E)");
            identity.Add("Accept-Language", "en-US,en;q=0.5");
            identity.Add("If-None-Match", "iu753id7");

            // set common headers
            for (int i = _identities.Count - 1; i >= 0; --i)
            {
                identity = _identities[i];
                // spoof the 'Via' heading
                var builder = StringBuilderCache.Get(64);
                builder.Append("1.1 ");
                builder.Append(Randomize.Byte);
                builder.Append(Chars.Stop);
                builder.Append(Randomize.Byte);
                builder.Append(Chars.Stop);
                builder.Append(Randomize.Byte);
                builder.Append(Chars.Stop);
                builder.Append(Randomize.Byte);
                identity.Add("Via", builder.ToString());

                // spoof the 'X-Forwarded-For' heading
                builder.Length = 0;
                builder.Append(Randomize.Byte);
                builder.Append(Chars.Stop);
                builder.Append(Randomize.Byte);
                builder.Append(Chars.Stop);
                builder.Append(Randomize.Byte);
                builder.Append(Chars.Stop);
                builder.Append(Randomize.Byte);
                identity.Add("X-Forwarded-For", StringBuilderCache.SetAndGet(builder));

                identity.Add("Accept-Encoding", "gzip, deflate");
                identity.KeepAlive = true;
            }
        }
Beispiel #10
0
        /// <summary>
        /// Resolve the specified path with the specified callback. If the path has a defined
        /// callback, it will be trimmed to a sub-path.
        /// </summary>
        public void Resolve(string path, IAction <string> onResolved)
        {
            // split the path into sections
            string[] sections = path.Split(Chars.ForwardSlash);

            int index = 0;

            if (sections[index] == string.Empty)
            {
                ++index;
            }

            int  subPathIndex = 0;
            bool first        = true;
            var  builder      = StringBuilderCache.Get();

            // iterate
            while (index < sections.Length)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    builder.Append(Chars.ForwardSlash);
                }

                builder.Append(sections[index]);
                ++index;
                // does the path contain a callback? yes, update the sub path
                if (_routes.ContainsKey(builder.ToString()))
                {
                    subPathIndex = index;
                }
            }

            // get the sub path
            builder.Length = 0;
            first          = true;
            while (subPathIndex < sections.Length)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    builder.Append(Chars.ForwardSlash);
                }

                builder.Append(sections[subPathIndex]);

                ++subPathIndex;
            }

            onResolved.ArgA = StringBuilderCache.SetAndGet(builder);
            onResolved.Run();
        }
Beispiel #11
0
        /// <summary>
        /// Gets the current formatted and filtered stack trace.
        /// </summary>
        /// <returns>Space separated list of methods</returns>
        public static string Get()
        {
#if !NETSTANDARD1_5
            var frames = new StackTrace().GetFrames();
#else // The above works in netstandard2.0 via https://github.com/dotnet/corefx/pull/12527
            StackFrame[] frames = null;
#endif
            if (frames == null || MiniProfiler.Settings.StackMaxLength <= 0)
            {
                return(string.Empty);
            }

            var sb          = StringBuilderCache.Get();
            int stackLength = 0,
                startFrame  = frames.Length - 1;

            for (int i = 0; i < frames.Length; i++)
            {
                var method = frames[i].GetMethod();
                if (stackLength >= MiniProfiler.Settings.StackMaxLength
                    // ASP.NET: no need to continue up the chain
                    || method.Name == "System.Web.HttpApplication.IExecutionStep.Execute" ||
                    (method.Module.Name == "Microsoft.AspNetCore.Mvc.Core.dll" && method.DeclaringType.Name == "ObjectMethodExecutor"))
                {
                    frames[i]  = null;
                    startFrame = i < 0 ? 0 : i - 1;
                    break;
                }
                else if (ShouldExcludeType(method) ||
                         MiniProfiler.Settings.AssembliesToExclude.Contains(method.Module.Assembly.GetName().Name) ||
                         MiniProfiler.Settings.MethodsToExclude.Contains(method.Name))
                {
                    frames[i] = null;
                }
                else
                {
                    stackLength += (stackLength > 0 ? 3 : 0) + method.Name.Length;
                }
            }

            for (var i = startFrame; i >= 0; i--)
            {
                var f = frames[i];
                if (f != null)
                {
                    var method = f.GetMethod();
                    if (sb.Length > 0)
                    {
                        sb.Append(" > ");
                    }
                    sb.Append(method.Name);
                }
            }

            return(sb.ToStringRecycle());
        }
Beispiel #12
0
        public void ReturnNotSameStringBuilderWithoutRecycle()
        {
            var sb1 = StringBuilderCache.Get();
            var sb2 = StringBuilderCache.Get();

            StringBuilderCache.Recycle(sb1);
            StringBuilderCache.Recycle(sb2);

            Assert.NotSame(sb1, sb2);
        }
Beispiel #13
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>
        /// <param name="htmlEncode">Whether to HTML encode the response, for use in a web page for example.</param>
        public static string RenderPlainText(this MiniProfiler profiler, bool htmlEncode = false)
        {
            if (profiler == null)
            {
                return(string.Empty);
            }

            var text = StringBuilderCache.Get()
                       .Append(htmlEncode ? WebUtility.HtmlEncode(Environment.MachineName) : Environment.MachineName)
                       .Append(" at ")
                       .Append(DateTime.UtcNow)
                       .AppendLine();

            var timings = new Stack <Timing>();

            timings.Push(profiler.Root);

            while (timings.Count > 0)
            {
                var timing = timings.Pop();

                text.AppendFormat("{0} {1} = {2:###,##0.##}ms",
                                  new string('>', timing.Depth),
                                  htmlEncode ? WebUtility.HtmlEncode(timing.Name) : timing.Name,
                                  timing.DurationMilliseconds);

                if (timing.HasCustomTimings)
                {
                    foreach (var pair in timing.CustomTimings)
                    {
                        var type          = pair.Key;
                        var customTimings = pair.Value;

                        text.AppendFormat(" ({0} = {1:###,##0.##}ms in {2} cmd{3})",
                                          type,
                                          customTimings.Sum(ct => ct.DurationMilliseconds),
                                          customTimings.Count,
                                          customTimings.Count == 1 ? string.Empty : "s");
                    }
                }

                text.AppendLine();

                if (timing.HasChildren)
                {
                    var children = timing.Children;
                    for (var i = children.Count - 1; i >= 0; i--)
                    {
                        timings.Push(children[i]);
                    }
                }
            }

            return(text.ToStringRecycle());
        }
Beispiel #14
0
        public void ReturnSameStringBuilderAfterRecycle()
        {
            var sb1 = StringBuilderCache.Get();

            sb1.ToStringRecycle();
            var sb2 = StringBuilderCache.Get();

            sb2.ToStringRecycle();

            Assert.Same(sb1, sb2);
        }
Beispiel #15
0
        internal static SettingsBuilder <TClass> AddCustomDataFromCustomAttributes <TClass>(this SettingsBuilder <TClass> settingsBuilder, HttpContext context, ControllerActionDescriptor controllerActionDescriptor, PerformanceMeterMvcOptions <TClass> options) where TClass : ControllerBase
        {
            if (options == null || options.AddCustomDataFromCustomAttributes)
            {
                foreach (MethodCustomDataAttribute methodCustomData in controllerActionDescriptor.MethodInfo.GetCustomAttributes(typeof(MethodCustomDataAttribute), false))
                {
                    settingsBuilder = settingsBuilder.CustomData(methodCustomData.Key, methodCustomData.Value);
                }
                if (context.Request.QueryString.HasValue)
                {
                    settingsBuilder = settingsBuilder.CustomData(QueryStringCustomDataKey, context.Request.QueryString.Value);
                }
                if (context.User.Identity.IsAuthenticated)
                {
                    settingsBuilder = settingsBuilder.CustomData(UserIdentityNameCustomDataKey, context.User.Identity.Name);
                }

                // add caller from attributes
                settingsBuilder = settingsBuilder.CallerFrom(context.Connection?.RemoteIpAddress?.ToString() ?? context.Connection?.LocalIpAddress?.ToString());
                foreach (MethodCallerAttribute methodCaller in controllerActionDescriptor.MethodInfo.GetCustomAttributes(typeof(MethodCallerAttribute), false))
                {
                    settingsBuilder = settingsBuilder.CallerFrom(methodCaller.Caller);
                }
            }

            // add route path to custom data
            if (options == null || options.AddRoutePathToCustomData)
            {
                var url = StringBuilderCache.Get()
                          .Append(context.Request.Scheme)
                          .Append("://")
                          .Append(context.Request.Host.Value)
                          .Append(context.Request.PathBase.Value)
                          .Append(context.Request.Path.Value)
                          .Append(context.Request.QueryString.Value)
                          .ToStringRecycle();

                var routeData = context.GetRouteData();
                if (routeData != null)
                {
                    settingsBuilder = settingsBuilder.CustomData(PathCustomDataKey, routeData.Values["controller"] + "/" + routeData.Values["action"]);
                }
                else
                {
                    if (url.Length > 50)
                    {
                        url = url.Remove(50);
                    }
                    settingsBuilder = settingsBuilder.CustomData(PathCustomDataKey, url);
                }
            }

            return(settingsBuilder);
        }
 private static string GetCounterName(string original)
 {
     return(CounterLookup.GetOrAdd(original,
                                   k => StringBuilderCache.Get()
                                   .Append(k)
                                   .Replace("\\", "_")
                                   .Replace("/", "_")
                                   .Replace("(", "[")
                                   .Replace(")", "]")
                                   .Replace("#", "_")
                                   .ToStringRecycle()));
 }
Beispiel #17
0
        /// <summary>
        /// Start compiling the script.
        /// </summary>
        public virtual void CompileAssembly()
        {
            CompilerParameters parameters;
            CodeDomProvider    provider;
            CompilerResults    results;

            provider   = CodeDomProvider.CreateProvider("CSharp");
            parameters = new CompilerParameters {
                GenerateExecutable    = false,
                GenerateInMemory      = true,
                TreatWarningsAsErrors = false
            };

            // add references to all the assemblies we might need
            _assembly = Assembly.GetExecutingAssembly();
            parameters.ReferencedAssemblies.Add(_assembly.Location);

            // iterate the referenced assemblies to find the target
            foreach (AssemblyName assemblyName in _assembly.GetReferencedAssemblies())
            {
                // add each referenced assembly
                parameters.ReferencedAssemblies.Add(Assembly.Load(assemblyName).Location);
            }

            // invoke compilation of the source file
            results = provider.CompileAssemblyFromSource(parameters, Script.ToString());

            // were there any errors with the compilation?
            if (results.Errors.Count > 0)
            {
                // get a builder for the cache
                StringBuilder builder = StringBuilderCache.Get();
                // append all compilation errors
                foreach (CompilerError error in results.Errors)
                {
                    builder.Append(error.ToString());
                    builder.Append('\n');
                }

                // run the error callback
                _onError.ArgA = builder.ToString();
                _onError.Run();
            }
            else
            {
                // persist the resulting assembly
                _assembly = results.CompiledAssembly;

                // run the compilation complete method
                OnCompiled();
            }
        }
Beispiel #18
0
        /// <summary>
        /// Get a hex string representation of this array of bytes.
        /// </summary>
        public static string ToString(this byte[] bytes)
        {
            var builder = StringBuilderCache.Get(bytes.Length * 2);

            if (bytes != null)
            {
                foreach (byte bit in bytes)
                {
                    builder.Append(HexStringTable[bit]);
                }
            }
            return(StringBuilderCache.SetAndGet(builder));
        }
Beispiel #19
0
        /// <summary>
        /// You can wrap an HTML block with timing wrappers using this helper
        /// </summary>
        /// <param name="name">The name of the block to time.</param>
        /// <param name="html">The HTML to wrap in this timing.</param>
        public static string TimeScript(string name, string html)
        {
            if (MiniProfiler.Current != null)
            {
                var sb = StringBuilderCache.Get();
                name = name.Replace("'", "\\'");
                sb.Append("<script>mPt.start('").Append(name).Append("')</script>");
                sb.Append(html);
                sb.Append("<script>mPt.end('").Append(name).Append("')</script>");
                return(sb.ToStringRecycle());
            }

            return(html);
        }
Beispiel #20
0
        public static string NetworkTextSummary(this Node info)
        {
            var sb = StringBuilderCache.Get();

            sb.Append("Total Traffic: ").Append(info.TotalPrimaryNetworkbps.ToSize("b")).AppendLine("/s");
            sb.AppendFormat("Interfaces ({0} total):", info.Interfaces.Count.ToString()).AppendLine();
            foreach (var i in info.PrimaryInterfaces.Take(5).OrderByDescending(i => i.InBps + i.OutBps))
            {
                sb.AppendFormat("{0}: {1}/s\n(In: {2}/s, Out: {3}/s)\n", i.PrettyName,
                                (i.InBps.GetValueOrDefault(0) + i.OutBps.GetValueOrDefault(0)).ToSize("b"),
                                i.InBps.GetValueOrDefault(0).ToSize("b"), i.OutBps.GetValueOrDefault(0).ToSize("b"));
            }
            return(sb.ToStringRecycle());
        }
Beispiel #21
0
        /// <summary>
        /// Build the javascript.
        /// </summary>
        public string Build()
        {
            String = StringBuilderCache.Get();
            foreach (var component in Components)
            {
                component.Build(this);
            }
            var componentsStr = String.ToString();

            String.Clear();
            foreach (var prototype in Prototypes)
            {
                prototype.Build(this);
            }
            return(StringBuilderCache.SetAndGet(String) + componentsStr);
        }
Beispiel #22
0
        public static string ApplicationMemoryTextSummary(this Node info)
        {
            if (info.Apps?.Any() != true)
            {
                return("");
            }

            var sb = StringBuilderCache.Get();

            sb.AppendFormat("Total App Pool Memory: {0}\n", info.Apps.Sum(a => a.MemoryUsed.GetValueOrDefault(0)).ToSize());
            sb.AppendLine("App Pools:");
            foreach (var a in info.Apps.OrderBy(a => a.NiceName))
            {
                sb.AppendFormat("  {0}: {1}\n", a.NiceName, a.MemoryUsed.GetValueOrDefault(0).ToSize());
            }
            return(sb.ToStringRecycle());
        }
Beispiel #23
0
        public static string ApplicationCPUTextSummary(this Node info)
        {
            if (info.Apps?.Any() != true)
            {
                return("");
            }

            var sb = StringBuilderCache.Get();

            sb.AppendFormat("Total App Pool CPU: {0} %\n", info.Apps.Sum(a => a.PercentCPU.GetValueOrDefault(0)).ToString(CultureInfo.CurrentCulture));
            sb.AppendLine("App Pools:");
            foreach (var a in info.Apps.OrderBy(a => a.NiceName))
            {
                sb.AppendFormat("  {0}: {1} %\n", a.NiceName, a.PercentCPU?.ToString(CultureInfo.CurrentCulture));
            }
            return(sb.ToStringRecycle());
        }
Beispiel #24
0
        /// <summary>
        /// Start a new page parser for the specified local file.
        /// </summary>
        public ElementParser(string localFile, IAction <ElementParser> onParsed = null)
        {
            Path    = localFile;
            _stream = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read);
            _reader = new ByteBuffer(_stream);

            _elementStack = new Stack <Element>();

            _builder = StringBuilderCache.Get();

            // perses the callback on parsed
            OnParsed = onParsed;

            // start as though reading an element body
            _section     = Section.Body;
            _skipContent = true;
        }
Beispiel #25
0
        public static IServer GetSingleServer(this ConnectionMultiplexer connection)
        {
            var endpoints = connection.GetEndPoints(configuredOnly: true);

            if (endpoints.Length == 1)
            {
                return(connection.GetServer(endpoints[0]));
            }

            var sb = StringBuilderCache.Get().Append("expected one endpoint, got ").Append(endpoints.Length).Append(": ");

            foreach (var ep in endpoints)
            {
                sb.Append(ep).Append(", ");
            }
            sb.Length -= 2;
            throw new InvalidOperationException(sb.ToStringRecycle());
        }
Beispiel #26
0
        /// <summary>
        /// Get a string representation of the post parameters.
        /// </summary>
        public override string ToString()
        {
            var builder = StringBuilderCache.Get();

            builder.Append("Post parameters [");
            // iterate the string parameters
            foreach (var parameter in ParamsStrings)
            {
                builder.Append(Chars.NewLine);
                builder.Append(parameter.Key);
                builder.Append(Chars.Equal);
                builder.Append(parameter.Value.Value);
                builder.Append(Chars.NewLine);
                foreach (var attribute in parameter.Value.Params)
                {
                    builder.Append(attribute.Key);
                    builder.Append(Chars.Colon);
                    builder.Append(attribute.Value);
                    builder.Append(Chars.SemiColon);
                    builder.Append(Chars.Space);
                }
            }
            // iterate the byte parameters
            foreach (var parameter in ParamsBytes)
            {
                builder.Append(Chars.NewLine);
                builder.Append(parameter.Key);
                builder.Append(Chars.Equal);
                builder.Append(parameter.Value.Value.Count);
                builder.Append("bytes");
                builder.Append(Chars.NewLine);
                foreach (var attribute in parameter.Value.Params)
                {
                    builder.Append(attribute.Key);
                    builder.Append(Chars.Colon);
                    builder.Append(attribute.Value);
                    builder.Append(Chars.SemiColon);
                    builder.Append(Chars.Space);
                }
            }
            builder.Append(Chars.NewLine);
            builder.Append(Chars.BracketSqClose);
            return(StringBuilderCache.SetAndGet(builder));
        }
Beispiel #27
0
        public static IHtmlContent OfAGs(IEnumerable <IMonitorStatus> ims, bool minimal = false)
        {
            if (ims == null)
            {
                return(HtmlString.Empty);
            }

            var sb   = StringBuilderCache.Get();
            var bad  = ims.Where(ag => ag.MonitorStatus != MonitorStatus.Good).ToList();
            var good = ims.Where(ag => ag.MonitorStatus == MonitorStatus.Good).ToList();

            if (minimal)
            {
                if (good.Count > 0)
                {
                    sb.Append(MonitorStatus.Good.Span(good.Count.ToComma(), good.Count.Pluralize("Healthy Database")));
                }
                sb.Append(" ");
                if (bad.Count > 0)
                {
                    if (good.Count > 0)
                    {
                        sb.Append(@"<span class=""text-muted"">/</span> ");
                    }
                    sb.Append(MonitorStatus.Critical.Span(bad.Count.ToComma(), bad.Count.Pluralize("Unhealthy Database")));
                }
            }
            else
            {
                if (bad.Count > 0)
                {
                    sb.Append(MonitorStatus.Critical.IconSpan()).Append(" ").Append(bad.Count.ToComma()).Append(" Unhealthy");
                }
                sb.Append(" ");
                if (good.Count > 0)
                {
                    sb.Append(MonitorStatus.Good.IconSpan()).Append(" ").Append(good.Count.ToComma()).Append(" Healthy");
                }
            }
            return(sb.ToStringRecycle().AsHtml());
        }
Beispiel #28
0
        public ActionResult Debug()
        {
            var sb = StringBuilderCache.Get()
                     .AppendFormat("Request IP: {0}\n", Current.RequestIP)
                     .AppendFormat("Request User: {0}\n", Current.User.AccountName)
                     .AppendFormat("Request Roles: {0}\n", Current.User.RawRoles)
                     .AppendLine()
                     .AppendLine("Headers:");

            foreach (string k in Request.Headers.Keys)
            {
                sb.AppendFormat("  {0}: {1}\n", k, Request.Headers[k]);
            }

            var ps = PollingEngine.GetPollingStatus();

            sb.AppendLine()
            .AppendLine("Polling Info:")
            .AppendLine(ps.GetPropertyNamesAndValues());
            return(TextPlain(sb.ToStringRecycle()));
        }
Beispiel #29
0
        private static FileResult SparkSVG <T>(IEnumerable <T> points, long max, Func <T, double> getVal, DateTime?start = null) where T : IGraphPoint
        {
            const int height = SparkHeight,
                      width  = SparkPoints;
            long nowEpoch    = DateTime.UtcNow.ToEpochTime(),
                 startEpoch  = (start ?? SparkStart).ToEpochTime(),
                 divisor     = max / 50;
            var range        = (nowEpoch - startEpoch) / (float)width;
            var first        = true;

            var sb = StringBuilderCache.Get().AppendFormat(@"<svg version=""1.1"" baseProfile=""full"" width=""{0}"" height=""{1}"" xmlns=""http://www.w3.org/2000/svg"" preserveAspectRatio=""none"">
  <line x1=""0"" y1=""{1}"" x2=""{0}"" y2=""{1}"" stroke=""{3}"" stroke-width=""1"" />
  <g fill=""{2}"" stroke=""none"">
    <path d=""M0 50 L", width.ToString(), height.ToString(), Color, AxisColor);

            foreach (var p in points)
            {
                var pos = (p.DateEpoch - startEpoch) / range;
                if (first && pos > 0)
                {
                    // TODO: Indicate a missing, ungraphed time portion?
                    sb.Append((pos - 1).ToString("f1", CultureInfo.InvariantCulture))
                    .Append(" ")
                    .Append(height)
                    .Append(" ");
                    first = false;
                }
                sb.Append(pos.ToString("f1", CultureInfo.InvariantCulture)).Append(" ")
                .Append((height - getVal(p) / divisor).ToString("f1", CultureInfo.InvariantCulture)).Append(" ");
            }
            sb.Append(width)
            .Append(" ")
            .Append(height)
            .Append(@" z""/>
   </g>
</svg>");
            var bytes = Encoding.UTF8.GetBytes(sb.ToStringRecycle());

            return(new FileContentResult(bytes, "image/svg+xml"));
        }
Beispiel #30
0
        private static List <string> ParseCsv(string line, bool allowEscape)
        {
            var result = new List <string>();
            var sb     = StringBuilderCache <LogFileModel> .Get();

            int  i  = 0;
            bool dq = false;

            while (i < line.Length)
            {
                char ch = line[i];
                switch (ch)
                {
                case '\"':
                    ++i;
                    if (i < line.Length && line[i] == '\"')
                    {
                        ++i;
                        sb.Append('\"');
                    }
                    else
                    {
                        dq = !dq;
                    }
                    break;

                case '\\' when allowEscape:
                    ++i;
                    if (i < line.Length)
                    {
                        ch = line[i];
                        ++i;
                        sb.Append(ch switch {
                            't' => '\t',
                            'v' => '\v',
                            'r' => '\r',
                            'n' => '\n',
                            _ => ch
                        });
                    }