0

I have written a code analyzer by using Roslyn APIs. The analyzer search for the hardcoded Urls in the code and fails the compilation of the code.

For example:

public class{

    public static string demo = "https://demo.com"; 
}

My analyser will fail the compilation of the above code saying it found the hard coded Url in the code.

There are some scenarios in which i want the analyzer to ignore the hardcoded urls error(in case its completely mandatory for the user to use it).

Is there anyway by which i will be able to give analyzer the signal to ignore the hardcoded Url.

I thought of using something like this:

public class{
    #region IGNORE HARDCODED URLS
    public static string demo = "https://demo.com"; 
    #endregion
}

But the problem with this approach is that i am unable to get all the variable declared inside the region IGNORE HARDCODED URLS.

Questions:

1.) Is this approach of using regions seems good for the use-case i am trying to solve? Is there any other better solutions you guys can think of and provide?

2.) If my approach looks good, then can somebody tell me how to get all the variables declared in the particular region?

1 Answers1

1

You can use #pragma warning directives to disable (and re-enable) analyzers for specific sections of code. Any analyzer diagnostic that was disabled by a #pragma warning disable directive will be ignored until the end of the file, or until you re-enable it with #pragma warning restore.

Assuming your analyzer has the ID AA0001, no diagnostic will be emitted for Demo in this example:

public class C
{
    #pragma warning disable AA0001

    public static string Demo = "https://example.com/";

    #pragma warning restore AA0001
}
jan.h
  • 524
  • 5
  • 11
  • If you wrote the analyzer, you define the ID yourself, usually in the field `DiagnosticId`. If you didn't write the analyzer and you have a piece of code that causes an analyzer diagnostic, you can find the ID in the Error List, in the Code column. – jan.h Aug 02 '18 at 11:22
  • This is what i was looking for. Thanks for the help. I can not upvote your answer cause my reputation is bad in stackoverflow. :P – Himanshu Verma Aug 02 '18 at 11:30