Last active
September 23, 2026 10:54
-
-
Save dresser/3924f6a97e7b362354d87b366120dae2 to your computer and use it in GitHub Desktop.
LINQPad script for parsing and aggregating Sitecore cache diagnostics files for analysis tuning.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <Query Kind="Program"> | |
| <Reference><RuntimeDirectory>\System.Windows.Forms.DataVisualization.dll</Reference> | |
| <Reference><RuntimeDirectory>\System.Windows.Forms.dll</Reference> | |
| <NuGetReference>HtmlAgilityPack</NuGetReference> | |
| <Namespace>HtmlAgilityPack</Namespace> | |
| <Namespace>System.Windows.Forms</Namespace> | |
| <Namespace>System.Windows.Forms.DataVisualization.Charting</Namespace> | |
| </Query> | |
| const double IncreaseThresholdPercent = 0.8; | |
| const double DecreaseThresholdPercent = 0.5; | |
| const double IncreaseFactor = 1.25; | |
| const double DecreaseFactor = 0.75; | |
| void Main() | |
| { | |
| using (var dialog = new FolderBrowserDialog | |
| { | |
| Description = "Select the folder containing cache statistics", | |
| ShowNewFolderButton = false | |
| }) | |
| if (dialog.ShowDialog() == DialogResult.OK) | |
| { | |
| string sourceFolder = dialog.SelectedPath; | |
| var outputFolder = $@"{sourceFolder}\output"; | |
| if (!System.IO.Directory.Exists(outputFolder)) | |
| { | |
| System.IO.Directory.CreateDirectory(outputFolder); | |
| } | |
| var outputFile = $@"{outputFolder}\cache_status_report.csv"; | |
| var sourceFiles = System.IO.Directory.GetFiles(sourceFolder, "*.html"); | |
| $"Found {sourceFiles.Count()} files".Dump(); | |
| $"Reading and parsing files now...".Dump(); | |
| var results = new List<CacheEntry>(); | |
| foreach (var sourceFile in sourceFiles) | |
| { | |
| results.AddRange(ReadCacheStatusFile(sourceFile)); | |
| } | |
| var groupedResults = results.GroupBy(r => r.Name).OrderBy(g => g.Key); | |
| var statistics = new List<CacheStatistics>(); | |
| foreach (var group in groupedResults) | |
| { | |
| var configUnit = group.First().MaxSizeUnits; | |
| var configValue = group.First().MaxSizeValue; | |
| var stat = new CacheStatistics | |
| { | |
| Name = group.Key, | |
| CountMin = group.Min(g => g.Count), | |
| CountMax = group.Max(g => g.Count), | |
| CountAverage = Math.Round(group.Average(g => g.Count), 2), | |
| SizeMin = Math.Round(ConvertBytesToUnit(group.Min(g => g.SizeBytes), configUnit), 2), | |
| SizeMax = Math.Round(ConvertBytesToUnit(group.Max(g => g.SizeBytes), configUnit), 2), | |
| SizeAverage = Math.Round(ConvertBytesToUnit(group.Average(g => g.SizeBytes), configUnit), 2), | |
| ConfigMaxSizeValue = configValue, | |
| ConfigMaxSizeUnit = configUnit, | |
| }; | |
| if (stat.SizeMax >= stat.ConfigMaxSizeValue * IncreaseThresholdPercent) | |
| { | |
| if (stat.CountMin == 0 && stat.CountMax == 0) | |
| { | |
| stat.NeedsAdjustment = false; | |
| stat.RecommendationMessage = $"Unused during capture window - verify before resizing."; | |
| } | |
| else | |
| { | |
| stat.NeedsAdjustment = true; | |
| var recommendedValue = Math.Round(stat.ConfigMaxSizeValue * IncreaseFactor, 2); | |
| stat.RecommendationMessage = $"Increase cache size to {recommendedValue} {stat.ConfigMaxSizeUnit}"; | |
| stat.RecommendedValue = recommendedValue; | |
| } | |
| } | |
| else if (stat.SizeMax < stat.ConfigMaxSizeValue * DecreaseThresholdPercent) | |
| { | |
| if (stat.CountMin == 0 && stat.CountMax == 0) | |
| { | |
| stat.NeedsAdjustment = false; | |
| stat.RecommendationMessage = $"Unused during capture window - verify before resizing."; | |
| } | |
| else | |
| { | |
| stat.NeedsAdjustment = true; | |
| var recommendedValue = Math.Round(stat.ConfigMaxSizeValue * DecreaseFactor, 2); | |
| stat.RecommendationMessage = $"Decrease cache size to {recommendedValue} {stat.ConfigMaxSizeUnit}"; | |
| stat.RecommendedValue = recommendedValue; | |
| } | |
| } | |
| else | |
| { | |
| stat.NeedsAdjustment = false; | |
| stat.RecommendationMessage = $"Cache size OK."; | |
| } | |
| statistics.Add(stat); | |
| } | |
| WriteStatisticsCsv(statistics, outputFile); | |
| $"Aggregated data written to {outputFile}".Dump(); | |
| var hotSpotCacheNames = statistics | |
| .Where(s => s.NeedsAdjustment) | |
| .Select(s => s.Name) | |
| .ToList(); | |
| var chartContainer = new DumpContainer().Dump("Chart"); | |
| var combo = new ComboBox { Width = 300, DropDownStyle = ComboBoxStyle.DropDownList }; | |
| combo.Items.AddRange(hotSpotCacheNames.Select(x => x).ToArray()); | |
| combo.SelectedIndexChanged += (s, e) => | |
| { | |
| var cacheName = hotSpotCacheNames[combo.SelectedIndex]; | |
| var cacheStats = statistics.FirstOrDefault(x => x.Name == cacheName); | |
| var cacheData = results | |
| .Where(r => r.Name == cacheName) | |
| .Select(x => new | |
| { | |
| Date = x.Date, | |
| Size = ConvertBytesToUnit(x.SizeBytes, x.MaxSizeUnits), | |
| ConfiguredSize = x.MaxSizeValue, | |
| RecommendedSize = cacheStats.RecommendedValue, | |
| Units = x.MaxSizeUnits | |
| }); | |
| var units = cacheData.First()?.Units; | |
| var chart = Util.Chart( | |
| cacheData, | |
| x => x.Date) | |
| .AddYSeries( | |
| x => x.Size, | |
| Util.SeriesType.Line, | |
| "Size") | |
| .AddYSeries( | |
| x => x.ConfiguredSize, | |
| Util.SeriesType.Line, | |
| "Configured Maximum") | |
| .AddYSeries( | |
| x => x.RecommendedSize, | |
| Util.SeriesType.Line, | |
| "Suggested Maximum") | |
| .ToWindowsChart(); | |
| chart.ChartAreas[0].AxisY.Title = $"Memory ({units})"; | |
| chart.ChartAreas[0].AxisX.Title = "Time"; | |
| chart.ChartAreas[0].AxisX.LabelStyle.Format = "dd/MM HH:mm"; | |
| chart.ChartAreas[0].AxisX.LabelStyle.Angle = -45; | |
| chart.ChartAreas[0].AxisY2.Enabled = AxisEnabled.False; | |
| chart.Titles.Add(cacheName); | |
| chartContainer.Content = chart.ToBitmap(); | |
| }; | |
| combo.Dump("Select a Cache"); | |
| } | |
| else | |
| { | |
| "No folder selected — aborting.".Dump(); | |
| return; // bail out of Main() early | |
| } | |
| } | |
| static readonly Dictionary<string, double> UnitMultipliers = new Dictionary<string, double> | |
| { | |
| {"bytes" , 1}, | |
| {"KB", 1024}, | |
| {"MB", 1024d * 1024}, | |
| {"GB", 1024d * 1024 * 1024}, | |
| }; | |
| class CacheEntry | |
| { | |
| public string Name { get; set; } | |
| public DateTime Date { get; set; } | |
| public long Count { get; set; } | |
| public double SizeBytes { get; set; } | |
| public double MaxSizeValue { get; set; } | |
| public string MaxSizeUnits { get; set; } | |
| } | |
| class CacheStatistics | |
| { | |
| public string Name { get; set; } | |
| public long CountMin { get; set; } | |
| public long CountMax { get; set; } | |
| public double CountAverage { get; set; } | |
| public double SizeMin { get; set; } | |
| public double SizeMax { get; set; } | |
| public double SizeAverage { get; set; } | |
| public double ConfigMaxSizeValue { get; set; } | |
| public string ConfigMaxSizeUnit { get; set; } | |
| public bool NeedsAdjustment { get; set; } | |
| public string RecommendationMessage { get; set; } | |
| public double RecommendedValue { get; set; } | |
| } | |
| List<CacheEntry> ReadCacheStatusFile(string fileName) | |
| { | |
| var results = new List<CacheEntry>(); | |
| var fileDate = ParseDateFromFileName(fileName); | |
| var doc = new HtmlAgilityPack.HtmlDocument(); | |
| doc.Load(fileName); | |
| var table = doc.DocumentNode.SelectSingleNode("//table"); | |
| if (table == null) return results; | |
| var rows = table.SelectNodes(".//tr"); | |
| if (rows == null || rows.Count < 2) | |
| return results; | |
| var headers = rows[0].SelectNodes("th|td") | |
| .Select(h => h.InnerText.Trim()) | |
| .ToList(); | |
| System.Diagnostics.Debug.Assert(headers[0].Equals("Name", StringComparison.CurrentCultureIgnoreCase), "Expected first column to be 'Name'"); | |
| System.Diagnostics.Debug.Assert(headers[1].Equals("Count", StringComparison.CurrentCultureIgnoreCase), "Expected second column to be 'Count'"); | |
| System.Diagnostics.Debug.Assert(headers[2].Equals("Size", StringComparison.CurrentCultureIgnoreCase), "Expected third column to be 'Size'"); | |
| System.Diagnostics.Debug.Assert(headers[3].Equals("MaxSize", StringComparison.CurrentCultureIgnoreCase), "Expected fourth column to be 'MaxSize'"); | |
| foreach (var row in rows.Skip(1)) | |
| { | |
| var cells = row.SelectNodes("td"); | |
| if (cells == null || cells.Count != headers.Count) | |
| continue; | |
| var maxSize = ParseSizeAndUnit(cells[3].InnerText.Trim()); | |
| var entry = new CacheEntry | |
| { | |
| Name = cells[0].InnerText.Trim(), | |
| Date = fileDate, | |
| Count = long.Parse(cells[1].InnerText.Trim()), | |
| SizeBytes = GetSizeInBytes(cells[2].InnerText.Trim()), | |
| MaxSizeValue = maxSize.value, | |
| MaxSizeUnits = maxSize.unit | |
| }; | |
| results.Add(entry); | |
| } | |
| return results; | |
| } | |
| DateTime ParseDateFromFileName(string fileName) | |
| { | |
| var name = System.IO.Path.GetFileNameWithoutExtension(fileName); | |
| var parts = name.Split('.'); | |
| var datePart = parts[1].TrimEnd('Z'); | |
| var timePart = parts[2].TrimEnd('Z'); | |
| return DateTime.ParseExact(datePart + timePart, "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture); | |
| } | |
| (double value, string unit) ParseSizeAndUnit(string sizeWithUnit) | |
| { | |
| var parts = sizeWithUnit.Split(' '); | |
| var value = double.Parse(parts[0]); | |
| var units = parts[1]; | |
| return (value, units); | |
| } | |
| double GetSizeInBytes(string sizeWithUnit) | |
| { | |
| var parsed = ParseSizeAndUnit(sizeWithUnit); | |
| if (!UnitMultipliers.TryGetValue(parsed.unit, out var multiplier)) | |
| throw new InvalidOperationException($"Unrecognized unit '{parsed.unit}'"); | |
| return parsed.value * multiplier; | |
| } | |
| double ConvertBytesToUnit(double valueInBytes, string unit) | |
| { | |
| if (!UnitMultipliers.TryGetValue(unit, out var multiplier)) | |
| throw new InvalidOperationException($"Unrecognized unit '{unit}'"); | |
| return valueInBytes / multiplier; | |
| } | |
| string Quote(object value) | |
| { | |
| return $"\"{value}\""; | |
| } | |
| void WriteStatisticsCsv(List<CacheStatistics> statistics, string fileName) | |
| { | |
| var stringBuilder = new System.Text.StringBuilder(); | |
| stringBuilder.AppendLine("\"Name\",\"CountMin\",\"CountMax\",\"CountAverage\",\"SizeMin\",\"SizeMax\",\"SizeAverage\",\"ConfigSizeValue\",\"ConfigSizeUnit\",\"NeedsAdjustment\",\"Recommendation\""); | |
| foreach (var line in statistics) | |
| { | |
| stringBuilder.AppendLine(Quote(line.Name) + "," + | |
| Quote(line.CountMin) + "," + | |
| Quote(line.CountMax) + "," + | |
| Quote(line.CountAverage) + "," + | |
| Quote(line.SizeMin) + "," + | |
| Quote(line.SizeMax) + "," + | |
| Quote(line.SizeAverage) + "," + | |
| Quote(line.ConfigMaxSizeValue) + "," + | |
| Quote(line.ConfigMaxSizeUnit) + "," + | |
| Quote(line.NeedsAdjustment) + "," + | |
| Quote(line.RecommendationMessage)); | |
| } | |
| File.WriteAllText(fileName, stringBuilder.ToString()); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See here for the accompanying article: https://www.matthewdresser.com/cms/sitecore/cache-stats-aggregation-script