To list all pages in a C# solution that contain inline CSS or inline script, along with the line number where it is found, you can use the following code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace InlineCodeAnalyzer
{
public class PageInfo
{
public string FilePath { get; set; }
public List<string> InlineCssLines { get; set; }
public List<string> InlineScriptLines { get; set; }
}
public class SolutionAnalyzer
{
public List<PageInfo> AnalyzeSolution(string solutionPath, string[] fileExtensions)
{
var pages = new List<PageInfo>();
var solutionFiles = GetSolutionFiles(solutionPath, fileExtensions);
foreach (var file in solutionFiles)
{
var page = AnalyzePage(file);
if (page != null)
pages.Add(page);
}
return pages;
}
private IEnumerable<string> GetSolutionFiles(string solutionPath, string[] fileExtensions)
{
var solutionFiles = new List<string>();
foreach (var extension in fileExtensions)
{
solutionFiles.AddRange(Directory.GetFiles(solutionPath, $"*.{extension}", SearchOption.AllDirectories));
}
return solutionFiles;
}
private PageInfo AnalyzePage(string filePath)
{
var lines = File.ReadAllLines(filePath);
var page = new PageInfo
{
FilePath = filePath,
InlineCssLines = new List<string>(),
InlineScriptLines = new List<string>()
};
for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++)
{
var line = lines[lineNumber];
if (line.Contains("<style>") || line.Contains("<script>"))
{
var closingTag = line.Contains("<style>") ? "</style>" : "</script>";
var inlineCodeLines = new List<string>();
while (!line.Contains(closingTag))
{
inlineCodeLines.Add(line);
lineNumber++;
line = lines[lineNumber];
}
inlineCodeLines.Add(line);
lineNumber++;
if (line.Contains("rel=\"stylesheet\""))
{
page.InlineCssLines.AddRange(inlineCodeLines);
}
else if (line.Contains("type=\"text/javascript\""))
{
page.InlineScriptLines.AddRange(inlineCodeLines);
}
}
}
return (page.InlineCssLines.Count > 0 || page.InlineScriptLines.Count > 0) ? page : null;
}
}
public class Program
{
public static void Main(string[] args)
{
var solutionPath = "path/to/your/solution";
var fileExtensions = new string[] { "aspx", "html", "cshtml" };
var analyzer = new SolutionAnalyzer();
var pages = analyzer.AnalyzeSolution(solutionPath, fileExtensions);
foreach (var page in pages)
{
Console.WriteLine("Page: " + page.FilePath);
if (page.InlineCssLines.Count > 0)
{
Console.WriteLine("Inline CSS:");
for (int i = 0; i < page.InlineCssLines.Count; i++)
{
Console.WriteLine($"Line {i + 1}: {page.InlineCssLines[i]}");
}
}
if (page.InlineScriptLines.Count > 0)
{
Console.WriteLine("Inline Scripts:");
for (int i = 0; i < page.InlineScriptLines.Count; i++)
{
Console.WriteLine($"Line {i + 1}: {page.InlineScriptLines[i]}");
}
}
Console.WriteLine();
}
}