From cc053ddbbf1ac3ad0584b58f0a70097c4fee3566 Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Tue, 30 Jan 2018 15:31:23 +0000 Subject: [PATCH] Better validation of C# class names in RazorCompiler --- .../Core/RazorCompilation/RazorCompiler.cs | 11 ++++++----- .../Microsoft.AspNetCore.Blazor.Build.csproj | 1 + 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.AspNetCore.Blazor.Build/Core/RazorCompilation/RazorCompiler.cs b/src/Microsoft.AspNetCore.Blazor.Build/Core/RazorCompilation/RazorCompiler.cs index 187cdfae6c..bf10a4ef63 100644 --- a/src/Microsoft.AspNetCore.Blazor.Build/Core/RazorCompilation/RazorCompiler.cs +++ b/src/Microsoft.AspNetCore.Blazor.Build/Core/RazorCompilation/RazorCompiler.cs @@ -9,7 +9,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text.RegularExpressions; +using System.CodeDom.Compiler; namespace Microsoft.AspNetCore.Blazor.Build.Core.RazorCompilation { @@ -18,9 +18,7 @@ namespace Microsoft.AspNetCore.Blazor.Build.Core.RazorCompilation /// public class RazorCompiler { - // TODO: Relax this to allow for whatever C# allows - private static Regex ClassNameRegex - = new Regex("^[a-z][a-z0-9_]*$", RegexOptions.IgnoreCase); + private static CodeDomProvider _csharpCodeDomProvider = CodeDomProvider.CreateProvider("c#"); /// /// Writes C# source code representing Blazor components defined by Razor files. @@ -150,12 +148,15 @@ namespace Microsoft.AspNetCore.Blazor.Build.Core.RazorCompilation // Use the filename as class name var inputBasename = Path.GetFileNameWithoutExtension(inputFilePathRelative); - if (!ClassNameRegex.IsMatch(inputBasename)) + if (!IsValidClassName(inputBasename)) { throw new RazorCompilerException($"Invalid name '{inputBasename}'. The name must be valid for a C# class name."); } return (resultNamespace, inputBasename); } + + private static bool IsValidClassName(string name) + => _csharpCodeDomProvider.IsValidIdentifier(name); } } diff --git a/src/Microsoft.AspNetCore.Blazor.Build/Microsoft.AspNetCore.Blazor.Build.csproj b/src/Microsoft.AspNetCore.Blazor.Build/Microsoft.AspNetCore.Blazor.Build.csproj index 6b14171c79..bd671c9af5 100644 --- a/src/Microsoft.AspNetCore.Blazor.Build/Microsoft.AspNetCore.Blazor.Build.csproj +++ b/src/Microsoft.AspNetCore.Blazor.Build/Microsoft.AspNetCore.Blazor.Build.csproj @@ -29,6 +29,7 @@ +