Search code examples
c#visual-studio

Is there a way to block a word (or RegEx) from compiling in C#?


I keep all of my project's "secrets" (API keys, database details, etc) outside the application and programmatically access those - both in development and in production. Is there a way, given a list of prohibited strings, I could set up Visual Studio to stop compiling if it sees one of them?

Just really trying not to commit them to the repo (...again).

I reviewed the options in the editorconfig, but that won't do the trick.


Solution

  • 1.You can use the pre-build event to call a simple script to check for cs files

    2.Custom Roslyn analyzer.

        private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true, description: Description);
    
        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();
            context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.StringLiteralExpression);
        }
        private void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            var literalExpression = (LiteralExpressionSyntax)context.Node;
            var literalValue = literalExpression.Token.ValueText;
    
            // Case insensitive check for "password" substring
            if (literalValue.IndexOf("password", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                var diagnostic = Diagnostic.Create(Rule, literalExpression.GetLocation(), literalValue);
                context.ReportDiagnostic(diagnostic);
            }
        }
    

    Unit Test:

    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System.Threading.Tasks;
    using VerifyCS = Analyzer1.Test.CSharpCodeFixVerifier<
        Analyzer1.Analyzer1Analyzer,
        Analyzer1.Analyzer1CodeFixProvider>;
    
    namespace Analyzer1.Test
    {
        [TestClass]
        public class Analyzer1UnitTest
        {
            //No diagnostics expected to show up
            [TestMethod]
            public async Task TestMethod1()
            {
                var test = @"
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        using System.Diagnostics;
    
        namespace ConsoleApplication1
        {
            class {|#0:TypeName|}
            {   
    public string str=""123password123"";
            }
        }";
    
                await VerifyCS.VerifyAnalyzerAsync(test);
            }
    
    1. As Jeremy said, use git hook.